Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

javascript - react render Logical && vs Ternary operator

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>
);
question from:https://stackoverflow.com/questions/65713434/react-render-logical-vs-ternary-operator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>
);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...