Get it right: null and undefined in JavaScript

Well, whenever I talk to developers, I find them in confusion about null and undefined in JavaScript. In this post I try to simplify understanding of null and undefined in JavaScript.

To start with null is language keyword and undefined in value of a variable. Both evaluates to value that indicates absence of a value.

To understand it better we can say null indicates an object with no value. Let us consider following code on null,


var result = typeof (null);
 console.log(result);

This will return you output as object. So to conclude we can say null is an object which contains no value or represents no object.

On the other hand undefined represents absence of value in a variable. Undefined is value of a variable. You get undefined value for a variable in following scenario

  • When variable is declared but not initialized
  • When function does not return a value
  • As value of function parameter which is not being passed
  • On accessing Array with index which does not exist
  • When accessing object property which does not exist

Let us consider following code on undefined,


var result = typeof (undefined);
 console.log(result);

This will return you output as undefined.

Other important difference is you cannot assigned undefined to a variable, whereas you can assign null to a variable. Undefined is read only.

Let us consider following code. It indicates that null and undefined represents same value that is absence of value but both are not same.


if (null == undefined) {
 console.log("both indicates absense of value");
 }

if (null === undefined) {
 console.log("both are same");
 }
 else {

console.log("both are not same");
 }

In last I will conclude that both undefined and null are falsy value in JavaScript. Both does not contain any property or methods.

I hope now you have better understanding on undefined and null in JavaScript. Thanks for reading.

4 responses to “Get it right: null and undefined in JavaScript”

  1. […] Get it right: null and undefined in JavaScript (Dhananjay Kumar) […]

  2. “Other important difference is you cannot assigned undefined to a variable, whereas you can assign null to a variable. Undefined is read only.”
    This is not true. You can assign any variable to have the value undefined, and you can even change the value of undefined (in older browsers at least) which makes it error prone.

    var c = undefined;
    var d = {‘c’ : c}
    console.log(d)
    > Object {c: undefined}
    console.log(“c” in d)
    > true

  3. “‘null’ is a keyword and ‘undefined’ a value.”
    Shouldn’t it be the other way around? ‘null’ is a value and ‘undefined’ a keyword? You’ve proven yourself wrong with “‘null’ is of type object”. That’s a value.

    And as Galiba stated, you can ofcourse assign ‘undefined’ to variables.

Leave a comment

Create a website or blog at WordPress.com