ES5 | When To Use Null And When To Use Undefined
Solution 1:
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 return null
to indicate that the resultset is empty. If your function has no return statement, implicitely undefined
is returned instead.
In general, always assign null
and never undefined
.
Solution 2:
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'.
Post a Comment for "ES5 | When To Use Null And When To Use Undefined"