Why is null
considered an object
in JavaScript?
Is checking
if ( object == null )
Do something
the
The following function shows why and is capable for working out the difference:
function test() {
var myObj = {};
console.log(myObj.myProperty);
myObj.myProperty = null;
console.log(myObj.myProperty);
}
If you call
test();
You're getting
undefined
null
The first console.log(...)
tries to get myProperty
from myObj
while it is not yet defined - so it gets back "undefined". After assigning null to it, the second console.log(...)
returns obviously "null" because myProperty
exists, but it has the value null
assigned to it.
In order to be able to query this difference, JavaScript has null
and undefined
: While null
is - just like in other languages an object, undefined
cannot be an object because there is no instance (even not a null
instance) available.