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

前端 未结 30 3660
眼角桃花
眼角桃花 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条回答
  •  我寻月下人不归
    2020-11-22 00:08

    ! check for empty strings (""), null, undefined, false and the number 0 and NaN. Say, if a string is empty var name = "" then console.log(!name) returns true.

    function isEmpty(val){
      return !val;
    }
    

    this function will return true if val is empty, null, undefined, false, the number 0 or NaN.

    OR

    According to your problem domain you can just use like !val or !!val.

提交回复
热议问题