The Wayback Machine - https://web.archive.org/web/20211214020939/https://www.geeksforgeeks.org/undefined-vs-null-in-javascript/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Undefined Vs Null in JavaScript

  • Last Updated : 05 Nov, 2020

There are several differences between null and undefined, which are sometimes understood as the same.

  1. Definition:

    Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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

    • Undefined: It means the value does not exist in the compiler. It is the global object.



  2. Type:

    Null: Object 

    Undefined: undefined

  3. You can see refer to “==” vs “===” article.

     
     null == undefined // true
     null === undefined // false
    

    It means null is equal to undefined but not identical.

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

  5. Differentiating using isNaN():
    You can refer to NaN article for better
    understanding.

    isNaN(2 +  null)      // false
    isNaN(2 + undefined) // true
    
  6. Examples:



    • Null:

      null ? console.log("true") : console.log("false") // false
      

      Null is also referred as false.

    • Undefined:

      When variable is not assigned a value

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

      Output:

       true

      Accessing values which does not exist

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

      Output:

      true
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!