Is there a standard function to check for null, undefined, or blank variables in JavaScript?

前端 未结 30 3658
眼角桃花
眼角桃花 2020-11-21 23:37

Is there a universal JavaScript function that checks that a variable has a value and ensures that it\'s not undefined or null? I\'ve got this code,

30条回答
  •  旧时难觅i
    2020-11-22 00:11

    function isEmpty(value){
      return (value == null || value.length === 0);
    }
    

    This will return true for

    undefined  // Because undefined == null
    
    null
    
    []
    
    ""
    

    and zero argument functions since a function's length is the number of declared parameters it takes.

    To disallow the latter category, you might want to just check for blank strings

    function isEmpty(value){
      return (value == null || value === '');
    }
    

提交回复
热议问题