What is the difference between 'null' and 'undefined' in JavaScript?

Introduction

In JavaScript, null and undefined are two special values that indicate the absence of a value. Although they are often used interchangeably, there is a subtle difference between them.

What is undefined in JavaScript?

undefined is a value automatically assigned to variables that have not been initialized or to object properties that do not exist. It is also returned by functions that do not explicitly return a value.

What is null in JavaScript?

On the other hand, null is a value explicitly assigned to a variable or object property to indicate that it has no value.

Here is a code example of undefined in JavaScript

let x;
console.log(x); // prints undefined

In this example, x is declared but not initialized, so its value is automatically set to undefined.

Another code example

function test() {}
console.log(test()); // prints undefined

In this example, test() is a function that does not return anything. When it is called, it implicitly returns undefined.

Here is a code example of null

let y = null;
console.log(y); // prints null

In this example, y is explicitly assigned the value null.

Now let's see how they behave in some operations,

let a;
let b = null;

console.log(a == undefined); // true
console.log(b == null); // true
console.log(a == null); // true
console.log(b == undefined); // true
console.log(a === undefined); // true
console.log(b === null); // true
console.log(a === null); // false
console.log(b === undefined); // false

The == operator checks if the values are equal, while the === operator checks if the values and types are equal. As you can see, undefined and null are equal when compared with ==, but not with ===.

Summary

In summary, undefined indicates a variable has not been assigned a value or a function does not have a return value. On the other hand, null indicates a variable or object property has no value.


Similar Articles