JavaScript null check

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

    Q: The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.

    A: Yes, data will be set to undefined. See section 10.5 Declaration Binding Instantiation of the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.

    Q: The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.

    Q: The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.

    A: Correct. Note that the following tests are equivalent:

    data != null
    data != undefined
    data !== null && data !== undefined
    

    See section 11.9.3 The Abstract Equality Comparison Algorithm and section 11.9.6 The Strict Equality Comparison Algorithm of the spec.

提交回复
热议问题