A value cannot be null unless it has specifically been assigned null. Let’s look at some code:
Above, on line 1 we are setting our value to null. null is powerful and something commonly found in code. There is even a null object design pattern.
“A variable that has not been assigned a value is of type
undefined” (Docs). If we declare a variable but do not assign a value to it, its value is undefined.
Since we didn’t assign a value to temp on line 1 it is undefined.
“A method or statement also returns
undefined if the variable that is being evaluated does not have an assigned value.” So we would see undefined if we access a property on an object that does not exist or does not contain a value.
We don’t need to be scared of undefined it just means the variable has never been assigned or does not exist.
null vs undefined equality gotcha
There is a bit of a gotcha when thinking about equality of null vs undefined. Let’s look at examples:
In the first strict equal (===) case, we get false returned. This is because both null and undefined evaluate to false BUT they are different object types. null is of type object while undefined is simply of type undefined.
That is why the second case of only loosely equal (==) we get true coming back. It’s important to realize the distinction that null & undefined are different types.
Having come from a .NET background I had not seen undefined before. With a little research and playing around with code, it all came together. I encourage you to open up your console window now and mess around a little with null and undefined!