DEV Community

Vijay SRJ
Vijay SRJ

Posted on

undefined vs null in Javascript

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

You can combine both the checks using ! operator like this:

if(!output){
   //logic here
}
Enter fullscreen mode Exit fullscreen mode

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/

Top comments (0)