I have noticed that many developers struggle with the appropriate use of "null" and "undefined" in JavaScript.
"Null" refers to the absence of any object value. It is primarily used when an object is not present.
console.log(typeof null) // 'object'
"Undefined" is used when something is not defined. If any attribute in an API is missing, it will be considered as "undefined".
let i;
console.error(typeof i) // undefined
Note: It is important to always compare attribute values with "undefined" when processing API responses.
I will be posting tricks I have been using in my journey.
So follow me on LinkedIn.
Top comments (2)
Hi.
It's tricky indeed.
I would suggest using back ticks when talking about
undefined
becausetypeof
returns string"undefined"
and notundefined
. Beginners might struggle on that too.So when you say one should compare attribute values to "undefined" I think you should say: compare with
undefined
:Above example is not much but it shows how to use
undefined
.This is pretty good.
The best explanation I have ever seen: