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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.