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

Why is null considered an object in JavaScript?

Is checking

if ( object == null )
      Do something

the same as

if ( !object )
      Do something

?

And also:

What is the difference between null and undefined ?


(name is undefined)

You: What is name ? (*)
JavaScript: name ? What's a name ? I don't know what you're talking about. You haven't ever mentioned any name before. Are you seeing some other scripting language on the (client-)side?

name = null;

You: What is name ?
JavaScript: I don't know.

In short; undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it's not known what the value is.

One thing to remember is that null is not, conceptually, the same as false or "" or such, even if they equate after type casting, ie

name = false;

You: What is name ?
JavaScript: Boolean false.

name = '';

You: What is name ?
JavaScript: Empty string


*: name in this context is meant as a variable which has never been defined. It could be be any undefined variable. However, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names to not have to be.


The difference can be summarized into this snippet:

alert(typeof(null));      // object
alert(typeof(undefined)); // undefined

alert(null !== undefined) //true
alert(null == undefined)  //true

Checking

object == null is different to check if ( !object ) .

The latter is equal to ! Boolean(object) ! Boolean(object) , because the unary ! operator automatically cast the right operand into a Boolean.

Since Boolean(null) equals false then !false === true .

So if your object is not null , but false or 0 or "" , the check will pass because:

alert(Boolean(null)) //false
alert(Boolean(0))    //false
alert(Boolean(""))   //false

null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object" . But that is actually a bug (that might even be fixed in ECMAScript 6).

The difference between null and undefined is as follows:

  • undefined : used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.

    > var noValueYet;
    > console.log(noValueYet);
    undefined
    
    > function foo(x) { console.log(x) }
    > foo()
    undefined
    
    > var obj = {};
    > console.log(obj.unknownProperty)
    undefined
    

    Accessing unknown variables, however, produces an exception:

    > unknownVariable
    ReferenceError: unknownVariable is not defined
    
  • null : used by programmers to indicate “no value”, eg as a parameter to a function.

  • Examining a variable:

    console.log(typeof unknownVariable === "undefined"); // true
    
    var foo;
    console.log(typeof foo === "undefined"); // true
    console.log(foo === undefined); // true
    
    var bar = null;
    console.log(bar === null); // true
    

    As a general rule, you should always use === and never == in JavaScript (== performs all kinds of conversions that can produce unexpected results). The check x == null is an edge case, because it works for both null and undefined :

    > null == null
    true
    > undefined == null
    true
    

    A common way of checking whether a variable has a value is to convert it to boolean and see whether it is true . That conversion is performed by the if statement and the boolean operator ! (“not”).

    function foo(param) {
        if (param) {
            // ...
        }
    }
    function foo(param) {
        if (! param) param = "abc";
    }
    function foo(param) {
        // || returns first operand that can't be converted to false
        param = param || "abc";
    }
    

    Drawback of this approach: All of the following values evaluate to false , so you have to be careful (eg, the above checks can't distinguish between undefined and 0 ).

  • undefined , null
  • Booleans: false
  • Numbers: +0 , -0 , NaN
  • Strings: ""
  • You can test the conversion to boolean by using Boolean as a function (normally it is a constructor, to be used with new ):

    > Boolean(null)
    false
    > Boolean("")
    false
    > Boolean(3-3)
    false
    > Boolean({})
    true
    > Boolean([])
    true
    
    链接地址: http://www.djcxy.com/p/76336.html

    上一篇: JavaScript检查null与undefined以及==和===之间的区别

    下一篇: 为什么null是一个对象,null和undefined有什么区别?