JavaScript null check

前端 未结 8 978
小鲜肉
小鲜肉 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:55

    In your case use data==null (which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)

    function test(data) {
        if (data != null) {
            console.log('Data: ', data);
        }
    }
    
    test();          // the data=undefined
    test(null);      // the data=null
    test(undefined); // the data=undefined
    
    test(0); 
    test(false); 
    test('something');

    Here you have all (src):

    if

    == (its negation !=)

    === (its negation !==)

    0 讨论(0)
  • 2020-12-04 06:58

    An “undefined variable” is different from the value undefined.

    An undefined variable:

    var a;
    alert(b); // ReferenceError: b is not defined
    

    A variable with the value undefined:

    var a;
    alert(a); // Alerts “undefined”
    

    When a function takes an argument, that argument is always declared even if its value is undefined, and so there won’t be any error. You are right about != null followed by !== undefined being useless, though.

    0 讨论(0)
提交回复
热议问题