Why is null an object and what's the difference between null and undefined?

后端 未结 22 1061
猫巷女王i
猫巷女王i 2020-11-22 02:58

Why is null considered an object in JavaScript?

Is checking

if ( object == null )
      Do something

the

相关标签:
22条回答
  • 2020-11-22 03:52

    For example window.someWeirdProperty is undefined, so

    "window.someWeirdProperty === null" evaluates to false while

    "window.someWeirdProperty === undefined" evaluates to true.

    Moreover checkif if (!o) is not the same as checking if (o == null) for o being false.

    0 讨论(0)
  • 2020-11-22 03:53

    The best way to think about 'null' is to recall how the similar concept is used in databases, where it indicates that a field contains "no value at all."

    • Yes, the item's value is known; it is 'defined.' It has been initialized.
    • The item's value is: "there is no value."

    This is a very useful technique for writing programs that are more-easily debugged. An 'undefined' variable might be the result of a bug ... (how would you know?) ... but if the variable contains the value 'null,' you know that "someone, somewhere in this program, set it to 'null.'" Therefore, I suggest that, when you need to get rid of the value of a variable, don't "delete" ... set it to 'null.' The old value will be orphaned and soon will be garbage-collected; the new value is, "there is no value (now)." In both cases, the variable's state is certain: "it obviously, deliberately, got that way."

    0 讨论(0)
  • 2020-11-22 03:55

    The other fun thing about null, compared to undefined, is that it can be incremented.

    x = undefined
    x++
    y = null
    y++
    console.log(x) // NaN
    console.log(y) // 0

    This is useful for setting default numerical values for counters. How many times have you set a variable to -1 in its declaration?

    0 讨论(0)
  • 2020-11-22 03:57

    Look at this:

       <script>
    function f(a){
      alert(typeof(a));
      if (a==null) alert('null');
      a?alert(true):alert(false);
    }
    </script>
                                              //return:
    <button onclick="f()">nothing</button>    //undefined    null    false
    <button onclick="f(null)">null</button>   //object       null    false
    <button onclick="f('')">empty</button>    //string               false
    <button onclick="f(0)">zero</button>      //number               false
    <button onclick="f(1)">int</button>       //number               true
    <button onclick="f('x')">str</button>     //string               true
    
    0 讨论(0)
提交回复
热议问题