DEV Community

Cover image for Don't use '&&' for conditional reasoning

Posted on • Updated on


Don't use '&&' for conditional reasoning

We often use '&&' to display a component if a given condition is true and to not display it when the condition is false.

function BigComponent({condition}) {
    return (
          <p> After this we will try to render a component based 
             on a condition 
          {condition && <NextComponent/>}

export default BigComponent
Enter fullscreen mode Exit fullscreen mode

So basically, here the condition is evaluated and only if the left side of '&&' is true, we move forward and then render the second half, that is the component.

This is called short circuiting.

There are two problems here:

  1. The output to the condition must be boolean. If the condition gives 0, it will render 0.

  2. If the result from the condition is undefined, it will give an error.

What to do then?

To avoid something like displaying a zero or getting an 🔴error🔴, we can use a ternary operator:

condition ? <ConditionalComponent /> : null

which translates to: "if condition is true do the first statement else execute the statement after the colon (:)"

Happy Coding!👩‍💻

Top comments (4)

brense profile image
Rense Bakker

Interesting argument. However, I would argue that if your conditional flag could be anything other than a boolean you shouldn't use it as a flag though... if it can be 0 than your condition should be myFlag !== 0 && <Component />.

Ps: thats a colon, semicolon is this one ; 😉

aishanipach profile image

Thanks for pointing the typo out!

Here, I have talked about specific use case where we can get a numerical value signifying a Boolean like 0 which is taken for false but would cause an issue while rendering. A flag always works in the case you mentioned.

alaindet profile image
Alain D'Ettorre

What about {!!condition && <NextComponent/>} and call it a day?

aishanipach profile image

That would be just to 'make it work' I suppose. Want to discuss best practices here

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!