Demystifying short-circuit conditions when you have a 0 on left hand side in JavaScript & ReactJS ;)
I learnt something recently while solving a bug… So why not share it with the world! Here we go…
The Problem?
The problem was, part of the ReactJS code was rendering a 0.
A simplified example:
conditionVariable && <MyComponent/>
Generally if the short circuit condition is true then MyComponent should be rendered, otherwise nothing should be rendered. So why I was seeing a 0 here?
In my case conditionVariable’s value was 0. Since 0 is falsy and number the left side was returned and rendered.
This is how JavaScipt’s logical AND operator (&&) works:
0 && <MyComponent/> // 0
1 && <MyComponent/> // MyComponent is rendered
false && <MyComponent/> // false - nothing rendered
true && <MyComponent/> // MyComponent is rendered
"someString" && <MyComponent/> // MyComponent is rendered
null && <MyComponent/> // null - nothing rendered
undefined && <MyComponent/> // undefined - nothing rendered
The Solution?
- Using ternary operator:
conditionVariable ? <MyComponent/> : null
2. Using double logical NOT (!!) operator to convert conditionVariable’s value to a boolean:
!!conditionVariable && <MyComponent/>
3. Anymore solutions that you know? Please share it in the comment box below.
Thanks for reading. :)
#javascript #reactjs #frontend #ui #programming