DEV Community

Shashank Soni
Shashank Soni

Posted on

2 2

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)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay