DEV Community

Cover image for JavaScript gotchas - not all your conditions are booleans

JavaScript gotchas - not all your conditions are booleans

Alois Sečkár on November 20, 2023

One thing I like about JavaScript is its shothand evaluation whether a variable contains a value. Instead of the tedious if (text !== undefined &am...
Collapse
 
lebbe profile image
Lars-Erik Bruce • Edited

I love this feature of JavaScript, but there are some gotchas developers should be aware of:

1) Empty arrays are truthy, one would easily have thought otherwise

!![]
true
Enter fullscreen mode Exit fullscreen mode

2) NaN is falsy. Instead of trying to check if a number is NaN, check if a number is falsy. this could be very handy in certain circumstances, except for that

3) The number 0 is falsy. Yep thats right, so if you use an if (number) { ...} to safeguard against NaN, you won't perform any computations on 0 as well.

In JSX, there is also an issue with conditions not being boolean, say in usages like this:

<div>
  {someVariable && <Component someProp={someVariable} />}
</div>
Enter fullscreen mode Exit fullscreen mode

If, somehow, someVariable is NaN here, the letters "NaN" would show up on the screen! I'm surpriced how often I've actually spotted "bugs" like this in applications I have maintained. Often they have gone unnoticed because it's been barely visible, or just been a temporary state. In cases like these, you can use !! to enforce someVariable to become a boolean as well, and React won't render booleans to the screen:

<div>
  {!!someVariable && <Component someProp={someVariable} />}
</div>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aloisseckar profile image
Alois Sečkár • Edited

Thank you for pointing out those exceptions. I got caught by 0 being falsy couple of times as well.

And btw my personal favorite among falsy JS values is document.all, although one probably won't use it so often in the actual code.