Ramin Ahmadi | Personal website of Ramin Ahmadi

Difference between null and undefined in JavaScript

As a front end developer you might have checked value of variables for null value or undefined. For example asking for a non-existing property of an object.

let cars = {};
console.log(cars.BMW);
//returns undefine

now a simple if statement will tell you if BMW exists in cars variable. Here is how to check for that:

let cars = {};
if (cars.BMW == undefined){
console.log("cars.BMW is not defined");
} else {
console.log(cars.BMW);
}

cars.BMW also doesn’t exists because cars doesn’t have any property. To prove that, we can write below statement:

let cars = {};
if (cars.BMW == null)
{
console.log("cars.BMW is not defined");
}
else {
console.log(cars.BMW);
}

Hold on Ramin, what you’re telling me is that null equals undefined?

Well, what don’t you test that with code. If null is equal to undefined you should get true result. Lets try that:

if (null  == undefined) {
console.log("it is true");
} else {
console.log("it is false");
}
// returns "it is true"

How about we check to see if null and undefined are identical:

if (null  === undefined) {
console.log("it is true");
} else {
console.log("it is false");
}
// returns "it is false

Now it’s confusing! Is cars.BMW a null value or undefined and which one you should check for when you need to access it in your code?

To understand the difference between Null and Undefined, we must look into their definition first.

Null

The value null represents the intentional absence of any object value

let  foo = null; 
foo;
// returns null

Undefined

Undefined is a variable that has not been assigned a value is of type undefined.

function testUndefined(testVariable) {
if (testVariable === undefined) {
return 'Undefined';
}
return t;
}
var x;

So in summery Null is an assigned value which means nothing but undefined is a type which indicates that a variable is declared but not defined yet.

When type–converting comparisons Null and Undefined (Null == undefined) JS converts both to the same type before making the comparison, both returning undefined, hence true return of if statement. However, when strict comparing Null and Undefined because their nature is different you will get false return.

Leave a Comment.