undefined vs null in Javascript
Vijay SRJ
Posted on April 20, 2021
If you are from the background of a programming language like Java , you might feel that the way to represent a “no value” is through the value “null”.
But Javascript has two ways to denote a “no value”.
One is “undefined”
Another is “null”
“undefined” represents “no value” whereas “null” represents “no object” to be more specific.
Thus the major difference is that null is concerned with objects only.
When does Javascript return undefined?
When a variable is declared but not initialized , javascript throws undefined.
Here is an example:
var x;
console.log(x); // the value returned here is undefined
If you try to invoke a property of an object which doesn’t exist , you get undefined:
var obj = {};
console.log(obj.name); // the value returned here is undefined
When does Javascript return null?
null means “missing”.
So you get null whenever an object is missing.
For example when you try to access a html element that does not exist , you get null.
The below code returns null if there is no html element named “name” :
<script>
console.log(document.getElementById("name"));
</script>
How to check if a function returns null or undefined?
Let’s say you are invoking a function in your javascript code and that function may return null or undefined. In that case you need to check for both null and undefined :
let output = somefunction();
if(output === undefined || output === null){
//logic here
}
You can combine both the checks using ! operator like this:
if(!output){
//logic here
}
This works because both undefined and null are treated as “false” by javascript.
But you need to be cautious here , because if the output of the function in the above examples is an empty string , still the value of output is “false”.
This is because javascript treats an empty string as false.
Also the below are treated as false:
0
NaN
false (the boolean value false itself)
To summarize , javascript considers all these as false:
false
0
”
undefined
null
NaN
Reposted from :
https://fullstackdeveloper.guru/2021/04/20/undefined-vs-null-in-javascript/
Posted on April 20, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.