0

I was following a tutorial when I saw the following code snippet. I couldn't find anything about the and operator being used in this way. Is this a react thing? Can someone explain this or link to documentation that explains it?


{basket?.length > 0 && (
    <div className="checkout__right">
        <h2>Subtotal</h2>
        <Subtotal />
    </div>
)}

sabertenn
  • 31
  • 4
  • 3
    It's just a bit more of a concise way to express this idea- since this operator short-circuits, if the first part is not truthy the second part will not be evaluated. – argentage Dec 20 '20 at 22:12
  • 1
    This is known as "short-circuit evaluation" https://typeofnan.dev/short-circuit-evaluation-in-javascript/ – Nick Dec 20 '20 at 22:13

1 Answers1

2

This idiom uses the fact that logical operators, such as && and || have short-circuit semantics. If the left hand operand of an && operator is a false, the right hand operand isn't evaluated, because the result would be false anyway.

Thus, && is used a conditional statement, evaluating the right hand operand only if the left hand operator is true.

Mureinik
  • 297,002
  • 52
  • 306
  • 350