liveBook · Manning

Logical AND operator

As explained in React Quickly, Second Edition

The logical AND operator evaluates operands from left to right and returns the first falsy operand or the final operand.

Use `&&` in JSX when an element should appear only if a condition is true: `{isVerified && <Checkmark />}`. JavaScript evaluates the left operand first. If it is falsy, the expression returns that value without evaluating the element; otherwise, it returns the element. section 3.2.6 section 3.4.3

Avoid a stray zero

A shopping cart might use `{items.length && <button>Checkout</button>}`. When the cart is empty, `items.length` is `0`, so the expression returns `0`—and JSX displays it. Use a Boolean comparison instead: `{items.length > 0 && <button>Checkout</button>}`. Now an empty cart produces `false`, which displays nothing. section 3.4.3

class ShoppingCart extends Component {
  render() {
    const hasItems = this.props.items.length > 0;   #1
    return (
      <aside>
        <h1>Shopping cart</h1>
        <CartItems items={this.props.items} />
        {hasItems && <button>Checkout</button>}     #2
      </aside>
    );
  }
}

The complete cart component names the Boolean condition `hasItems` before using it to show the Checkout button. section 3.4.3

Keep `&&` for optional elements. Use a ternary when you need one element or another; for more complex branching, consider a separate component. section 3.2.6

How React Quickly, Second Edition covers it

How deep it goes
Explains short-circuit results and the visible-zero pitfall, then replaces a numeric guard with a Boolean comparison.
Examples
Shows a verification checkmark and a shopping-cart Checkout button that can accidentally display `0`.
What it assumes
Builds on JavaScript conditions and truthiness while demonstrating their use in JSX component rendering.
What you can do after
Apply it via React JSX to show optional elements while avoiding stray zeroes from numeric conditions.
How it connects
Connects JavaScript truthiness and short-circuit evaluation to JSX rendering, ternary operators, and React component branching.

Also explained in

Compare how 7 books explain logical AND operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.