JS: 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 JS: 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 http://www.2ality.com/2013/10/typeof-null.html , 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 pair; you cannot add properties to null.

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

[see JS: Object Type]

What's the Use of “null”

There are 2 major uses of null.

What's 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: JS: 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 JS: 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 use null in Object.create() to create a object with no parent. [see JS: Object.create]

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

ECMAScript 2015 §ECMAScript Data Types and Values#sec-ecmascript-language-types-null-type

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog