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?
JavaScript
x
7
1
return (
2
<div>
3
<div>{x === 1 && <div>Hello</div>}</div>
4
<div>{x === 1 ? <div>Hello</div> : null}</div>
5
</div>
6
);
7
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:
JavaScript
1
26
26
1
const count: number | null = 0;
2
const firstName: number | null = "";
3
4
return (
5
<div>
6
{/* Was this a bug or is `0` really not supposed to render??
7
* This will just render "0". */}
8
<div>{count && <>The count is {count}</>}</div>
9
10
{/* Okay got it, there's a difference between `null` and `number` */}
11
<div>
12
{count == null ? <>No count at all</> : <>Count of {count}</>}
13
</div>
14
15
{/* Was this a bug too or is `""` supposed to render nothing?
16
* This will just render an empty string. */}
17
<div>{firstName && <>My name is {firstName}</>}</div>
18
19
{/* Okay now I see `null` / `undefined` vs. a string */}
20
<div>
21
{firstName == null ? <>No name</> : <>This *will* render {firstName}</>}
22
</div>
23
</div>
24
);
25
26