In this article we will understand the concept of "undefined", "NaN" and "null" in JavaScript

Understand “undefined” ,“NaN” and “null“ in JavaScript

In this article we will learn the concept of “undefined” ,“NaN”
and “null” in JavaScript. Two concepts are very much important to debug any
JavaScript application. Let’s try to understand them.

“Undefined” in JavaScript

Before understanding the concept of “undefined” we have to
understand the concept of “window” object in JavaScript. “Window” object is
called super object in JavaScript which represents the whole window or browser
screen. When we create any variable or object, it automatically attach to
window object. In other words, if the variable or function is defined then it will
attach to window object. In one example we will see the concept.

<script>var val = 100;

console.log(window.val);</script>

Here we have declared val and then accessing with the help
of “window” object. And we are getting value 100. Now, if the variable is not present in “window”
object and if we try to access it, then it will throw “undefined” error. Have a
look on below example.

Here we did not define “val” variable and we are trying to
print the value. As it is not defined in window object, it’s throwing “undefined’
exception. This is true not only in case of variable but also in case of class/object.

So, in conclusion, when we want to access any value which is
not defined in window objects it’s throwing “undefined” exception.

“NaN” in JavaScript

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

<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="JavaScript.aspx.cs"Inherits="JavaScript.JavaScript"%><!DOCTYPEhtml><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"></head><body><formid="form1"runat="server"><script>var number = 'not a number';

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

</script></form></body></html>

We are seeing that it’s throwing NaN exception.

“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” with the
help of “window” object. It’s showing that the value is “null” means not
defined. Then we are checking whether “null” and empty are same or not.