Open In App

Undefined Vs Null in JavaScript

In JavaScript, both undefined and null represent the absence of a meaningful value, but they are used in slightly different contexts. In this article, we are going to learn the difference between Undefined and null in JavaScript.

undefined

Example: In the example, we have shown undefined.






let x; // variable declared but not initialized
console.log(x); // Output: undefined
 
function doSomething() {
  // no return statement, so the function returns undefined
}
console.log(doSomething()); // Output: undefined
 
let obj = {};
console.log(obj.property); // Output: undefined

Output
undefined
undefined
undefined

null

Example: In the example, we have shown null.






let y = null; // variable intentionally set to null
console.log(y); // Output: null
 
let obj = { property: null }; // property intentionally set to null
console.log(obj.property); // Output: null

Output
null
null

You can see refer to “==” vs “===” article.

 null == undefined // true
null === undefined // false

It means null is equal to undefined but not identical.

When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.

Difference between undefined and null

Undefined Null
Undefined means a variable has been declared but has yet not been assigned a value. Null is an assignment value. It can be assigned to a variable as a representation of no value. 
It is an ECMAScript1 (ES1) feature. It is a Primitive value in Javascript

It does not have any syntax. But you can assign undefined to any variable but we do not do that.

Its syntax is -:

null

It is a global property.

It is not a global property.

Its supported browsers are -:

Chrome , Microsoft Edge , Internet Explorer , Firefox , Safari , Opera Mini

Its supported browsers are -:

Chrome , Microsoft Edge , Internet Explorer , Firefox , Safari , Opera Mini


Article Tags :