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

后端 未结 22 1040
猫巷女王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: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."

提交回复
热议问题