DEV Community

Cover image for null !== undefined
Mohd Ahshan Danish
Mohd Ahshan Danish

Posted on • Updated on

null !== undefined

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
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
joolsmcfly profile image
Julien Dephix

Hi.

It's tricky indeed.

I would suggest using back ticks when talking about undefined because typeof returns string "undefined" and not undefined. Beginners might struggle on that too.

let i;
console.log(typeof i);  // "undefined" and not undefined
Enter fullscreen mode Exit fullscreen mode

So when you say one should compare attribute values to "undefined" I think you should say: compare with undefined:

const myAPIResponse = {id: 12, name: "Jools"}

if (myAPIResponse.status === undefined) {
    // bla bla
}
Enter fullscreen mode Exit fullscreen mode

Above example is not much but it shows how to use undefined.

Collapse
 
kaamkiya profile image
Kaamkiya

This is pretty good.

The best explanation I have ever seen:

Image description