DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for JSByte: How to check falsy values with null or undefined in JavaScript
Shruti Kapoor
Shruti Kapoor

Posted on • Updated on

JSByte: How to check falsy values with null or undefined in JavaScript

I will be sharing bite sized learnings about JavaScript regularly in this series. Follow along with me as I re-learn JavaScript. This series will cover JS fundamentals, browsers, DOM, system design, domain architecture and frameworks.

console.log( null === undefined )
Enter fullscreen mode Exit fullscreen mode

Rule

An important rule of checking type with null or undefined is that in the equality equation above, the result will be true only if both sides are either null or undefined.

This is helpful in checking against falsy values such as following -

let c;
console.log(c == null);
// true

console.log(c == undefined);
// true

console.log(0 == null);
// false

console.log("" == null);
// false

Enter fullscreen mode Exit fullscreen mode

One caveat: == should be rarely used. This is a good use case for when == can be used. If you are unsure whether to use == or ===, use ===.


Interested in more JSBytes? Sign up for the newsletter

Top comments (2)

Collapse
 
merri profile image
Vesa Piittinen

The only thing I'd like to add is that this is the only case you should ever use == for comparison, and always otherwise use ===. This is a good rule to follow especially if you're working without TypeScript or other type enforcement tool as it greatly reduces bugs caused by mixing datatypes.

Collapse
 
shrutikapoor08 profile image
Shruti Kapoor Author

Good point! Updating the post.

🀯

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs