Possible Duplicate:
Javascript null or undefined
null
is a reserved word but not a keyword.
Hence it can not be over-written.
undefined
is a built in global that can be over-written. This is why you see jQuery re-define it in its IIFE. Just to make sure it was not over-written.
What it the technical distinction of when to use each as specified in ES 5.
I know that I have seen browsers set an un-created localStorage property to either null or undefined depending upon the browser.
localStorage.not_defined === null // sometimes
localStorage.not_defined === undefined // sometimes
How does ES 5 specify their usage in this case and in general?
ES5 provides not clarification:
8.1 The Undefined Type The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.
8.2 The Null Type The Null type has exactly one value, called null.
http://www.ecma-international.org/publications/standards/Ecma-262.htm
The distinction of these two is rather vague and not clarified in the spec.
The common sense is the following:
undefined
are variables which never have been assigned and non-existing properties.null
however is a state of a variable or property which indicates that it has no value assigned.Some methods like
getElement...
explicitely returnnull
to indicate that the resultset is empty. If your function has no return statement, implicitelyundefined
is returned instead.In general, always assign
null
and neverundefined
.null is a value. The value of nothing is null.
undefined is the lack of a value.
This is how it should be used.
you should never assign undefined to anything. That defeats the purpose. If you want to make your existing property undefined you use the delete keyword.
On the other hand null is a legitimate value to assign to a variable.
jQuery adds an undefined variable to its closure because it is easier to test a === undefined than to write typeof a === 'undefined'.