Difference between "null"  and  "undefined"

Difference between "null" and "undefined"

·

1 min read

When you begin your JavaScript developer journey, you encounter null and undefined keywords while practising coding.

A question might have arisen in your head, "Are they the same or is there a difference between them?"

Let's check what are types of them first.


console.log(typeof null); // object
console.log(typeof undefined); // undefined

undefined

When we declare a variable, JavaScript assigns "undefined" as a default value to it during the phase of memory allocation. The variable keeps this value until we explicitly assign a new one.

let name; 
console.log(name); // undefined

name = "Jhon"; // explicitly assign a new value
console.log(name);// Jhon

null

We use it when we want to set a variable's value to nothing, Or when we want to point an object to empty.

let user = { // user points to an object
    name: "Holy"
};

user = null; // user points to nothing