W3docs

The Difference Between Null and Undefined in JavaScript

Read this JavaScript tutorial and get relevant information about the differences between null and undefined data types. Find out their similarities as well.

Many of you confuse Null and Undefined. However, there are differences and peculiarities that we are going to discuss in this tutorial.

undefined is a global property and a primitive value, not a variable. It represents a variable that has been declared, but its value has not yet been assigned.

Null is a JavaScript primitive value and represents the intentional absence of any object value. That is to say, it can be assigned to a variable as a representation of no value.

For example, let’s assign the value of null to a variable:

Javascript the value of null

javascript— editable

Typically, undefined means a variable that has been declared but not assigned a value:

Javascript declared not defined

javascript— editable

From the above example, you already know that undefined is a type itself, while null is a primitive value, not an object.

But why does the typeof operator return “object” for a null value? It was an error in the original JavaScript implementation that was then copied into ECMAScript. Today, null is technically a primitive value, despite this historical typeof bug.

However, when checking for null or undefined, remember the differences between equality (==) and identity (===) operators, as equality performs type conversion. In practice, == null is commonly used to check for both null and undefined simultaneously.

Javascript null and undefined equality

javascript— editable

To sum up, in JavaScript null means "nothing" or "empty"—something that does not exist—while undefined represents a variable that has been declared but not assigned a value.