w3docs logo
  1. Snippets
  2. JavaScript
  3. The Difference Between Null and Undefined in JavaScript

The Difference Between Null and Undefined in JavaScript

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 variable in the global scope. The default value of undefined is the primitive value undefined. Undefined means a variable that has been declared, but the value of that variable has not yet been assigned.

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

For exmple, let’s assign the value of null to test:

w3docs logo Javascript the value of null
let value1 = null; console.log(value1); // null

Typically, undefined means a variable that has been declared not defined:

w3docs logo Javascript declared not defined
let value2; console.log(value2); // undefined

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

But why the typeof operator returns “object” for a null value? It was an error in the original JavaScript implementation that was then copied in ECMAScript. Today, null is considered a placeholder for an object, despite the fact of technically being a primitive value.

However, when checking for null or undefined, remember the differences between equality (==) and identity (===) operators, as equality performs type-conversion.

w3docs logo Javascript null and undefined equality
console.log(typeof null); // "object" console.log(typeof undefined); // "undefined" console.log(null === undefined); // false console.log(null == undefined );// true console.log(null === null ); // true console.log(null == null); // true console.log(!null ); // true

To sum up, in JavaScript null means "nothing" and “empty”, something that does not exist. And, a variable without a value called undefined.

Do you find this helpful?