DEV Community

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

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.