Difference between undefined and null

Difference between undefined and null

In this blog, we are going to cover the difference between undefined and null. This is the topic that confuses a lot of new JavaScript learners. Let's have a read on the topic in detail.

Table Of Content

  • Overview
  • undefined
  • null
  • Conclusion

Overview

In JavaScript there exist both undefined and null, if you take a high-level look at both of them you will see that directly or indirectly they both represent nothingness.

  • Main thing you need to keep in mind here is that undefined is a type whereas null is an object.

undefined

Whenever you declare a variable and do not explicitly assign any value to that variable its implicit value becomes undefined.

For example

let food;
console.log(food)

// output
// undefined

As discussed above, we've declared a food variable in the above code snippet but we've not given any explicit value to that variable. So, JavaScript will implicitly assign the value of undefined to the variable.

Other cases where you can have undefined value

  • When you assign a return value of a function to a variable but that function doesn't return a value.
  • When you try to access the value from an array or an object which doesn't exist.

null

null also represent the nothingness that is a value of nothing. We explicitly tell the interpreter that this variable has the value of null.

Example

let food = null
console.log(food)

// output -> null

Let's say you go to market with a food basket and someone asks you what's inside that basked you say null means nothing here you are explicitly telling that your basked is empty.

Conclusion

In JavaScript undefined and null both are ways to show the empty state but in a different way. undefined can be an implicit value assigned by the language but null will never be assigned by language itself. The user is supposed to assign a value of null. After that, undefined means the absence of any value in general whereas null means that the variable has been explicitly told to be empty.