DEV Community

Shashank Soni
Shashank Soni

Posted on

Null vs Undefined in Javascript

Null is an assignment value. It can be assigned to a variable as a representation of no value:

There are two features of null you should understand

  1. null is an empty or non-existent value.
  2. null must be assigned
  3. When you assign null to a variable, you are declaring that this value is explicitly empty.
 let age = null;
 console.log(age); // null
Enter fullscreen mode Exit fullscreen mode

Undefined usually means a variable has been declared, but not defined.

When you try to access a property of an object that doesn't exist you will get undefined in return.

const shashank = {
    name : 'Shashank',  
}

console.log(shashank.age) // undefined
Enter fullscreen mode Exit fullscreen mode
  • Both nulland undefinedare primitive values in JavaScript.
  • When you do loose equality check on both it returns true
null == undefined // true
Enter fullscreen mode Exit fullscreen mode

because both are considered falsy values.

Summary

  • null is an assigned value. It means nothing.
  • undefined typically means a variable has been declared but not defined yet.
  • null and undefined are falsy values.
  • null!== undefined (strict equality) , but null == undefined ( loose equality)

Top comments (0)