Some JavaScript data types can be a little difficult to understand, this is somewhat due to how JavaScript was initially written. For example:
null + null = 0
null / null = NaN
1 + null = 1
null === 0 //=> false
null == 0 //=> false
console.log(null) //=> undefinednull === undefined //=> false
In the case above ‘null’, while having the properties of ‘0’ is not equal to 0, while returning undefined is not equal to undefined, and when added to a number equals said number. This sounds like some sort of riddle, but there is some logic behind the way JavaScript’s null works.
Null is a representation of no value. Like ‘0’, null plus another number would equal said number but, unlike 0 which represents a value similar to empty, null represents literally nothing.
Now to add more to the nature of null, its the only “nothing” value that can (or rather should)be assigned to a variable. This means that cases like this:
let thisValue = null
console.log(thisValue) //=> null
are completely valid. This brings us to the other “nothing” datatype, ‘undefined’.
Undefined compared to null is less than nothing. It usually means that the variable being return wasn’t assigned anything at all:
let thatValue
console.log(thatValue) //=> undefined
So to summarize, null is a value that represents ‘nothing’ that can be assigned to a variable, while undefined is the default value to undefined variables. This can be a little tricky to fully wrap your head around at times so here’s the perfect picture to describe “null” vs “0" vs “undefined”: