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
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. </head>  
  5. <body>  
  6.     <script>  
  7.         var val = 200;  
  8.         console.log(window.val);  
  9.     </script>  
  10. </body>  
  11. </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.
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <script>  
  8.         console.log(window.val);  
  9.     </script>  
  10.     </form>  
  11. </body>  
  12. </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.
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <script>  
  8.         var number = 'not a number';  
  9.         console.log('Value is :- ' + Number(number));  
  10.     </script>  
  11.     </form>  
  12. </body>  
  13. </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.
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. </head>  
  5. <body>  
  6. <form id="form1" runat="server">  
  7. <script>  
  8.     var val = null;  
  9.     console.log(window.val);  
  10.     if (val == "") {  
  11.         console.log('empty and null are same');  
  12.     }  
  13.     else  
  14.         console.log('empty and null are not same');  
  15. </script>  
  16. </form>  
  17. </body>  
  18. </html>   
null
 

Summary

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