Undefined Vs Null in JavaScript

Undefined Vs Null in JavaScript

JavaScript includes two additional primitive type values – null and undefined, that can be assigned to a variable that has special meaning.

Null :

It is the intentional absence of the value. It is one of the primitive values of JavaScript.

You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value

When we define a variable to null then we are trying to convey that the variable is empty

Example: null

var myVaAr = null;

alert(myVarA); // null 

In the above example, null is assigned to a variable myVarA. It means we have defined a variable but have not assigned any value yet, so value is absence.

A null value evaluates to false in conditional expression. So you don’t have to use comparison operators like === or !== to check for null values.

Example: null in conditional expression

var myVarA = null;

if (myVarA)
    alert("myVarA is not null");
else
    alert("myVarA is null" );

undefined :

undefined means the value does not exist in the compiler. It is the global object. Undefined is also a primitive value in JavaScript. A variable or an object has an undefined value when no value is assigned before using it. So you can say that undefined means lack of value or unknown value.

The type of Undefined is undefined.

When we define a variable to undefined then we are trying to convey that the variable does not exist .

Example: Undefined

var temp;
if(temp === undefined)
console.log("true");
else
console.log("false");

Output is: true

 

Accessing values which does not exist

var temp=['1','2','3'];
if(temp[3] === undefined)
console.log("true");
else
console.log("false");

Output is : true

 Points to Remember for Undefined Vs Null in JavaScript:

1 Comment

Leave a Reply

Your email address will not be published.