DEV Community

Pandu Rijal Pasa
Pandu Rijal Pasa

Posted on

Difference Between null And undefined In Javascript (with Notes)

You might be thinking that null & undefined is the same. You have to know that, spoiler alert, they are not. What I mean by this is: yes both have many similarities, but deep down it's totally different.

It's confusing, I know. But you need to know these basic things. So let's jump!

Similarity

Both of them usually called nullish value: have either null or undefined value. These also listed as falsy values, which are:

  • null
  • undefined
  • false
  • 0 (zero) —(also for -0 and 0n)
  • “” (empty string)
  • NaN (Not a Number)

Falsy values itself means that the value will be generated as false on the boolean approach.

Difference

Alt Text

From the definition, null is an intentional absence of a value. While undefined is a default value for a variable with no value assigned.

const bowl = null; //null

const bowl; //undefined

As mentioned above, both are falsy values. Even so, it works this way:

null  == undefined
null !== undefined

Why? Because when it comes to type, it's totally different. Javascript defines null as an empty object, hence if you do typeof null it will show "object". While undefined is a primitive value. The type of undefined will be "undefined" itself.

If we try to make equalization on a number format, null will be identified as a 0 (zero), while undefined will not be recognized as any number (NaN). Like this:

const addNum = 8 + null // 8
const addNum = 8 + undefined // NaN

Conclusion

Both undefined and null have the same value, the same nullish and falsy, but each has a different type. Hence use in its own place.

Top comments (3)

Collapse
 
amt8u profile image
amt8u

Looks like you covered all the differences between null and undefined. Though I already have an opinion, would like to know what do you think about their application? Which one should be used when? More precisely why null exist if undefined was already there to signify abswnce of value?

Collapse
 
bias profile image
Tobias Nickel

please people, when ever you can, use undefined. it even is javascripts default value when something is not there.

Collapse
 
edupooter profile image
Eduardo Pooter Reis

Why did you write "the bowl is not exist"? The correct form would be "the bowl doesn't exist".