ES5 | When to use null and when to use undefined

ecmascript-5, javascript

Solution

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`.

Problem

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

Original source

Related problems