Both null and undefined can be regarded as a special value that indicates "no value".
The null is a language keyword (in fact, it is a primitive ) which is used to indicate the expected lack of value. On the other hand, undefined is a predefined global variable that has a deeper meaning and is used to indicate an error-like, unexpected lack of value.
When your function has no return value, it returns undefined. If you declare a variable and don't initialize it, it returns the undefined value. If you query a non-existent array element or object property, again an undefined is returned. Here is an example.
- var book;
- alert(book); // => undefined
- alert(typeof book); // => undefined
If you want to indicate the 'lack of value' in your code, you typically use null rather than undefined.
- var book = null;
- alert(book); // => null
- alert(typeof book); // => object (although null is not a true object)
Both null and undefined qualify as false when a Boolean value is required. They don't have any properties. If you attempt to access a property on them, an exception will be raised.
It is interesting to note that undefined is implemented as a global variable named 'undefined'. Its value is undefined. Since it is a global variable, there is nothing that prevents a malicious coder from re-assigning the value of undefined to something else, like so:
- // hacker's code
- undefined = true;