‘null’ vs ‘undefined’ in JavaScript: What is the Difference?

In JavaScript Technology

null vs undefined are 2 of the datatypes of Javascript out of 8 basic data types.

Developers using JavaScript misinterpret the difference between null and undefined. In JavaScript technology, like in any other programming languages, there are values which should say ‘I don’t exist’. In JavaScript technology, that value is null. The undefined value is the second one in JavaScript that indicates an absence.

Value undefined is a predefined global variable (not a language keyword like null) that is initialized to the undefined value. In ECMAScript 3, undefined is a read/write variable, and it can be set to any value. This error is corrected in ECMAScript 5 and undefined is read-only in that version of the language. If you apply the type of operator to the undefined value, it returns undefined, indicating that this value is the sole member of a special type.

Example: if a declared variable is undefined

var x;
if (typeof x === "undefined") {
  txt = "x is undefined";
} else {
  txt = "x is defined";
}

Example: if a not declared variable is undefined

if (typeof y === "undefined") {
  txt = "y is undefined";
} else {
  txt = "y is defined";
}

null and undefined both indicate an absence of value. The equality operator == considers them to be equal. (Use the strict equality operator === to distinguish them.) Both are falsy values—they behave like false when a boolean value is required. Neither null nor undefined have any properties or methods. In fact, using . or [] to access a property or method of these values causes a TypeError. [JavaScript: The Definitive Guide, 5th Edition]

Check if a variable is null or undefined…

If the variable is null:

if (a === null)
// or
if (a == null) // but see note below

If the variable is undefined:

if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below

References