undefined. This leads to a lot of confusion, so in this article I will break down the differences between
Null vs Undefined
To start I want to explain what
undefined have in common since they are very similar. Both
undefined mean that there is no value. If a variable is set to
undefined it has no value and if a function returns
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
If you want to learn more about double and triple equals check out my complete article on the topic linked here.
This is pretty much where the similarities end, though.
It is easiest to start with
null when comparing the differences between
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
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.
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
let a console.log(a) // undefined
Where this gets a bit confusing is the fact that you can set a variable to
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
undefined other than how they interact with double and triple equals, but if you are diligent in your use of
undefined you can write cleaner code that can make use out of the implicit/explicit nature of