Null vs undefined

JavaScript is quite confusing when it comes to a variable not having a value because it can be null or undefined. This leads to a lot of confusion, so in this article I will break down the differences between null and undefined.

To start I want to explain what null and undefined have in common since they are very similar. Both null and undefined mean that there is no value. If a variable is set to null or undefined it has no value and if a function returns null or undefined then it is saying it has no value to return. This you most likely already understand.

These values are actually so similar that they are considered equal when comparing with double equals (==).

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

Because of this, when I want to check to see if a variable has a value or not I almost always use double equals comparison since it will return true whether the variable is null or undefined.

Null:

It is easiest to start with null when comparing the differences between null and undefined since null is very straightforward. If a variable is null then it means the variable has no value and that it was explicitly set to have no value by the programmer. A variable will never be null unless somewhere in the code a programmer set a variable to null.

This is important to know since when you see a null value you know that the programmer who wrote that code is telling you there is no value explicitly. A great example of where null is useful is in something like a find function that queries a database for an entry. If no entry exists it makes the most sense to return null since you are stating that there is no value found.

Undefined:

On the other hand undefined means that there is no value because no value has been set yet. For example, if you create a variable and do not assign it a value then it will be undefined.

let a console.log(a) // undefined

Where this gets a bit confusing is the fact that you can set a variable to undefined.

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

a = undefined console.log(a) // undefined

The reason you would want to do this is to essentially reset a variable. By setting a variable to undefined you are conveying the message that the variable no longer contains any useful information, while if the value is null then you are specifically saying the result of some action has no value.

Technically, these both indicate no value, but they convey that message in slightly different ways.

Overall it is not super important to know the differences between null and undefined other than how they interact with double and triple equals, but if you are diligent in your use of null and undefined you can write cleaner code that can make use out of the implicit/explicit nature of null and undefined.