Null and Undefined in JavaScript. What is the difference?

Null and Undefined in JavaScript. What is the difference?

The keywords Null and undefined in JavaScript can be a struggle to understand. What are they? In what ways are they the same? And in what ways do they differ? In this tutorial, you will learn about these two keywords.

Undefined

When JavaScript says a variable is undefined, it means the variable has been declared but it is yet to be initialized. In other words, the variable is present in your program but has not been assigned a value.

Undefined is engine assigned (i.e. it is assigned by the JavaScript engine). You (as a programmer) can assign it to a variable too. However, this is widely not regarded as best practice.

Consider the example below. The firstName variable has been declared. However, it has not yet been initialized (no value has been assigned to it). Therefore, JavaScript refers to it as undefined.

let firstName
console.log(firstName) // undefined

Also, when we attempt to access or reference a property of an object that is non-existent, the result is undefined.

let player = {
  team: "Bulls",
  number: 23
}

console.log(player.name) // undefined

The player object has no name property. Thus, accessing player.name will results in undefined.

Null

Null is used to denote a non-existent value. Or a value that is deliberately left empty.

Unlike undefined, it is not assigned by the JavaScript engine. You can assign it to a variable when there is the need to denote the variable in question as empty or void.

let unicorn = null
console.log(unicorn) // null

In the example above, the unicorn variable exists alright but its value is empty or void.

Comparing Undefined and Null

console.log(null == undefined) // true
console.log(null === undefined) // false

When we use the double equal (==) to compare null and undefined, it returns true. This is because, under the hood, JavaScript recognizes both of them as empty.

However, when we use the strict equality (===) to compare null and undefined, it returns false. They are both of different types, hence they are not strictly equal. (Check below)

console.log(typeof(null)) // object
console.log(typeof(undefined)) // undefined

Conclusion

That's all folks! You now know about the difference between null and undefined. You can explain the difference between these two often confusing terms in JavaScript.

Thanks for reading.

Let's connect on LinkedIn | Twitter