null Vs undefined in JavaScript

It is very important to know that both are data types in JavaScript. Null is an assigned value to the variable whereas undefined is a variable which is declared but its value has not been assigned. When you do not declare the value, JavaScript assigns the value “undefined”.

let a;  //undefined
let b = null; //null

Let’s talk about the similarities between null and undefined. Both are considered false when you convert it into the boolean.

console.log(Boolean(a)); // false 
console.log(Boolean(b)); //false

JavaScript considers them similar because both represents the empty value but if compared with strict equality, it will get false. since null is type of object and undefined is type of undefined.

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

undefined is the default value of a variable which has not been assigned with specific value. It is the default value of a property which does not exist in an object. It is also the default value of a function which returns nothing or is missing its action.

let gender;
function showMessage(){}
let new_obj = {
   name : "Mary",
   gender : "Female",
}

console.log(gender); //undefined
console.log(showMessage()); //undefined
console.log(new_obj["a"]); //undefined

I hope this post was helpful to you. If you like my post, follow me @twitter/andramazo.

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top