Well, whenever I talk to developers, I find them in confusion about null and
undefined in JavaScript. In this post I try to simplify understanding of null
and undefined in JavaScript.
To start with null is language keyword and undefined in value of a variable.
Both evaluates to value that indicates absence of a value.
To understand it better we can say null indicates an object with no value. Let
us consider following code on null,
var result = typeof (null);
console.log(result);
This will return you output as object. So to conclude we can say null is an
object which contains no value or represents no object.
On the other hand undefined represents absence of value in a variable. Undefined
is value of a variable. You get undefined value for a variable in following
scenario
- When variable is declared but not
initialized
- When function does not return a value
- As value of function parameter which is
not being passed
- On accessing Array with index which does
not exist
- When accessing object property which does
not exist
Let us consider following code on undefined,
var result = typeof (undefined);
console.log(result);
This will return you output
as undefined.
Other important difference is you cannot assigned undefined to a variable,
whereas you can assign null to a variable. Undefined is read only.
Let us consider following code. It indicates that null and undefined represents
same value that is absence of value but both are not same.
if (null == undefined) {
console.log("both indicates absense of value");
}
if (null === undefined) {
console.log("both are same");
}
else {
console.log("both are not same");
}
In last I will conclude that both undefined and null are falsy value in
JavaScript. Both does not contain any property or methods.
I hope now you have better understanding on undefined and null in JavaScript.
Thanks for reading.