Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Refactoring the ternary operator

I am quite stuck in a refactored ternary operator while learning react. Here is the code I came across inside a JSX:

{props.openSpots === 0 && <div className="card--badge">SOLD OUT</div>}

I would like to ask why this will return the card–badge div? I am only familiar with the complete common ternary operator that looks like this instead:

{props.openSpots === 0 ? <div className="card--badge">SOLD OUT</div> : null}

Thank you very much.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

AND operator looks for the second argument if the first argument is true.

But, if first argument is false it does not look for second argument, and directly returns false.

true && statement == statement;

false && statement == false;

console.log(
    true && "I am visible"
)
console.log(
   '  ' && "I am visible"
)

console.log(
    false && "I am not visible"
)
console.log(
    0 && "I am not visible"
)
console.log(
   null && "I am not visible"
)
console.log(
   undefined && "I am not visible"
)

console.log(
   true && '' && "I am not visible"
)

Link for reference

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading