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
- 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;
console.log(x);
function doSomething() {
}
console.log(doSomething());
let obj = {};
console.log(obj.property);
|
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 ;
console.log(y);
let obj = { property: null };
console.log(obj.property);
|
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 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
Share your thoughts in the comments
Please Login to comment...