JavaScript null check

前端 未结 8 997
小鲜肉
小鲜肉 2020-12-04 06:20

I\'ve come across the following code:

function test(data) {
    if (data != null && data !== undefined) {
        // some code here
    }
}
         


        
8条回答
  •  一生所求
    2020-12-04 06:40

    In JavaScript, null is a special singleton object which is helpful for signaling "no value". You can test for it by comparison and, as usual in JavaScript, it's a good practice to use the === operator to avoid confusing type coercion:

    var a = null;
    alert(a === null); // true
    

    As @rynah mentions, "undefined" is a bit confusing in JavaScript. However, it's always safe to test if the typeof(x) is the string "undefined", even if "x" is not a declared variable:

    alert(typeof(x) === 'undefined'); // true
    

    Also, variables can have the "undefined value" if they are not initialized:

    var y;
    alert(typeof(y) === 'undefined'); // true
    

    Putting it all together, your check should look like this:

    if ((typeof(data) !== 'undefined') && (data !== null)) {
      // ...
    

    However, since the variable "data" is always defined since it is a formal function parameter, using the "typeof" operator is unnecessary and you can safely compare directly with the "undefined value".

    function(data) {
      if ((data !== undefined) && (data !== null)) {
        // ...
    

    This snippet amounts to saying "if the function was called with an argument which is defined and is not null..."

提交回复
热议问题