views:

158

answers:

3

Possible Duplicate:
Null object in javascript

Hi, I've read this thread about null in JavaScript, but I'm very confused about the identity of null now.

As it is known that typeof(null) evaluates to object because of the language design error, and ECMA states that null is The Null Type.

   8.2 The Null Type
   The Null type has exactly one value, called null.

So why people keep saying that null is an object?

I've asked my senior engineer, and he said null is a singleton object. Is that how everybody sees the null as in JavaScript too?

Thanks

+6  A: 

No, null is one of the few primitive types (others being numbers, strings, booleans, and undefined). Everything else is an object, including functions, arrays and regular expressions. Numbers, strings and booleans are often called "object-like", because they have methods, but they are immutable. Objects on the other hand are mutable.

Daniel Vassallo
Mutability has nothing to do with being an object. See Object.freeze in EcmaScript 5 which allows creation of immutable objects. Native objects in EcmaScript 3 are also objects and can be immutable. Null is not an object because it can respond to no messages -- has no properties or methods. This is why (null instanceof type) is false for all type.
Mike Samuel
@mikesamuel: Removed the "offending" part from my answer :)
Daniel Vassallo
+4  A: 

Null is the absence of an object. Undefined means it hasn't been assigned yet, and null means it has been assigned to be nothing.

Null is not really a singleton object, because dereferencing it will cause an error; for (var x in null) will give you an error. Think back to the pointer days; null was the value a pointer had when it was not pointing to an object.

Anthony Mills
`for (var x in null);` will not throw on many browsers, although it should, at least as specified on the [3rd edition](http://bclary.com/2004/11/07/#a-12.6.4) of ECMAScript (the `ToObject` operation will throw when the value is `null` or `undefined`). But this has changed, now on [ECMAScript 5](http://www.ecma262-5.com/ELS5_HTML.htm#Section_12.6.4), if the expression is `null` or `undefined`, the statement simply ends (a normal statement completion).
CMS
Nice, ECMA spec on HTML format. I was long looking for that! :)
c411
+3  A: 

null can't be considered an object because it cannot have properties. It is a keyword representing a primitive, like true and false.

> true instanceof Object
false
> null instanceof Object
false
no