DEV Community

Discussion on: React Clean Code - Simple ways to write better and cleaner code

Collapse
 
vedovelli profile image
Fábio Vedovelli

Thanks for the article. I see several people advocating against short-circuiting with &&, as you stated in your first example. By using short-circuit you run into the risk of ending up with a rendered the number 0 (zero) instead of your component.

Collapse
 
thawkin3 profile image
Tyler Hawkins

Thanks Fábio! That's true, to an extent. There was some good discussion in another thread and a reference to a Kent Dodds blog post where he advocates against using &&.

I do think it's important to note that the issue isn't necessarily with short-circuiting and the && operator, but rather from misusing it or misunderstanding how short-circuiting works.

For example, you can avoid rendering "0" in your UI from writing myArray.length && <MyComponent /> by instead using any of the following:

  • myArray.length > 0
  • !!(myArray.length)
  • Boolean(myArray.length)

But it's true that using the ternary makes it so you don't have to think about this and can just write: myArray.length ? <MyComponent /> : null.

So it really comes down to personal preference and the tradeoff of whether you like having the extra : null in your code or if you can remember to be careful in how you evaluate the length of an array in your conditional.