Can someone explain this line of code? (react/js)

I’ve never really used ternary operators, but I understand how to use them. However, this line of code doesn’t really make sense to me

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

the line of code is found in the block of code below.
I’m reading it as (if props.openSpots === 0 is true && ???)

from what he’s saying in the tutorial the div should only render if this condition is true but I’m not understanding the second part after the &&. I do understand the && operator, just not what comes after it in this example.

I’ve never been exposed to this before.

export default function Card(props) {
    return (
        <div className="card">
            {props.openSpots === 0 && <div className="card--badge">SOLD OUT</div>}
            <img src={`../images/${props.img}`} className="card--image" />
            <div className="card--stats">
                <img src="../images/star.png" className="card--star" />
                <span>{props.rating}</span>
                <span className="gray">({props.reviewCount}) • </span>
                <span className="gray">{props.location}</span>
            </div>
            <p className="card--title">{props.title}</p>
            <p className="card--price"><span className="bold">From ${props.price}</span> / person</p>
        </div>
const openSpots = 0;
const expression = openSpots === 0 && 'something';
console.log(expression) // displays something

This is known as short-circuit evaluation.

In your code, if props.openSpots === 0 evaluates to true, then the part after the && gets rendered.

1 Like

Thank you! that clears things up a lot.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.