Understand Undefined ,NaN and Null in JavaScript

Introduction

This article explains undefined, NaN and null in JavaScript. Two concepts are very important for debugging JavaScript applications. Let's try to understand them.

"Undefined" in JavaScript

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

</head>

<body>

    <script>

        var val = 200;

        console.log(window.val);

    </script>

</body>

</html>

Here we have declared val and then accessed it using the "window" object. And we are getting the value 200. Now, if the variable is not present in the "window" object and if we try to access it, then it will throw an "undefined" error. Have a look at the following example.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

</head>

<body>

    <form id="form1" runat="server">

    <script>

        console.log(window.val);

    </script>

    </form>

</body>

</html>

 
Undefined 
 
"NaN" in JavaScript

The acronym "NaN" is for Not a Number. Type conversion is a very common operation in any programming language. In JavaScript the Number() function converts other data types to a number type if compatible. Now, if the current type is not compatible with the number type then it throws a "NaN" exception. In this example we are trying to convert a string to a number and obviously it is not possible in JavaScript. Have a look at the example below.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

</head>

<body>

    <form id="form1" runat="server">

    <script>

        var number = 'not a number';

        console.log('Value is :- ' + Number(number));

    </script>

    </form>

</body>
</
html>

NaN

 "null" in JavaScript

The concept of "null" is that it is declared but the value is not defined. In this example we are checking the value of "val" using "window" object. It's showing that the value is "null" in other words not defined. Then we are checking whether "null" and empty are the same or not.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

</head>

<body>

<form id="form1" runat="server">

<script>

    var val = null;

    console.log(window.val);

    if (val == "") {

        console.log('empty and null are same');

    }

    else

        console.log('empty and null are not same');

</script>

</form>

</body>

</html> 

null 

Summary

In this article we learned the concept of "undefined", "NaN" and "null".

Up Next
    Ebook Download
    View all
    Learn
    View all