JavaScript: null

By Xah Lee. Date: . Last updated: .

What is “null” in JavaScript?

JavaScript has a literal value of null. For example, you can write let x = null;

null is one of the type of JavaScript values, and it is the only value of that type.

[see Value Types]

typeof null

typeof null return "object".

console.log( typeof null === "object" ); // true
// this is a historical bug
// typeof null should return "null"

Why “typeof null” return "object"

typeof null return "object" is a historical implementation bug. Now we are stuck with it. See: [The history of “typeof null” By Dr Axel Rauschmayer. At , accessed on 2015-10-28 ]

null is not a object, because It doesn't have the defining quality of JavaScript objects, namely, it's not a collection of key/value pairs; you cannot add properties to null.

null.p = 4;  // TypeError: Cannot set property 'p' of null

[see Object Type]

What is the Use of “null”

There are 2 major uses of null.

What is the Difference Between “null” and “undefined”?

undefined is the value when a variable isn't assigned, property doesn't exist, value of function that doesn't have return statement, value of function args not given, out of bound array access, etc. See: undefined .

null is the value of a object's internal slot [[prototype]] when the object doesn't have a parent, such as root object. [see Prototype and Inheritance]

JavaScript the language does not restrict how you use null or undefined.

In general, you can pass undefined as argument in function call, as if no argument is given. Such as in setUserData("John", undefined, 23). (But exact behavior of the function depends on the function.)

You can also use null as initial value of a variable.

JavaScript Special Literals

JavaScript in Depth