2

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.

  • 1
    Does this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND and this: https://stackoverflow.com/a/7310120/3977134 help you? – r3dst0rm Jul 18 '22 at 07:33
  • You have and `a && b` statement here. It's not a ternary operator. It's logical "and" This will return `b` if `a` is true, otherwise it will be false, and will simply return nothing. This will return the `div` if `props.openSpots === 0`. Otherwise nothing will be rendered. – pbialy Jul 18 '22 at 07:35
  • `&&` evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; _if all values are truthy, the value of the last operand is returned._ – sujeet Jul 18 '22 at 07:36
  • During the lesson it was first coded with the more familiar ternary operator then changed with the one I questioned above. This brought the confusion in me whether it is ternary operator or not -- or is it just a refactored one. – Kristof Villanueva Jul 18 '22 at 07:57

2 Answers2

2

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

Hritik Sharma
  • 1,756
  • 7
  • 24
  • 1
    Thanks @8bitIcon, edit is very helpful for the users. Found it really helpful. Will try to add links to the reference from next time. – Hritik Sharma Jul 18 '22 at 07:44
1

From the react documentation:

It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

See: https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator

Markus
  • 1,909
  • 4
  • 26
  • 54