In the react render()
when the value of x equals 1 both the logical && and ternary operator will display Hello and both are syntactically correct. I always used the && when I don’t want to show the else part of my condition, but I have come across one code base where most of the places they used ternary operator with null instead of &&. Is there any performance gain or any other advantage of using one method over the other?
return ( <div> <div>{x === 1 && <div>Hello</div>}</div> <div>{x === 1 ? <div>Hello</div> : null}</div> </div> );
Advertisement
Answer
There’s no significant performance difference, but because 0
and empty string ""
are “falsy” in JavaScript I always opt for the ternary operator so the next person to edit my code knows my exact intention.
Example:
const count: number | null = 0; const firstName: number | null = ""; return ( <div> {/* Was this a bug or is `0` really not supposed to render?? * This will just render "0". */} <div>{count && <>The count is {count}</>}</div> {/* Okay got it, there's a difference between `null` and `number` */} <div> {count == null ? <>No count at all</> : <>Count of {count}</>} </div> {/* Was this a bug too or is `""` supposed to render nothing? * This will just render an empty string. */} <div>{firstName && <>My name is {firstName}</>}</div> {/* Okay now I see `null` / `undefined` vs. a string */} <div> {firstName == null ? <>No name</> : <>This *will* render {firstName}</>} </div> </div> );