Open In App

Undefined Vs Null in JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

  • When a variable is declared but not initialized, or when a function does not return a value, the variable or the function’s result is undefined.
  • Accessing an object property or array element that does not exist also results in undefined.
  • It is a primitive value.

Example: In the example, we have shown undefined.

Javascript




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

  • It is a deliberate assignment that represents the absence of any object value.
  • It is often used to explicitly indicate that a variable or object property should have no value or no reference to any object.
  • It is also a primitive value.

Example: In the example, we have shown null.

Javascript




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



Last Updated : 26 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads