liveBook · Manning

Truthiness

As explained in React Quickly, Second Edition

Truthiness is the JavaScript behavior by which a value is treated as true or false in a Boolean context.

A checkout button that leaves a 0 behind

Consider `{items.length && <button>Checkout</button>}`. With an empty cart, `items.length` is 0. The `&&` expression returns that 0, and React displays it instead of displaying nothing. section 3.4.3

Truthiness is how JavaScript treats a value when a Boolean decision is needed. A truthy value acts like `true`; a falsy value acts like `false`. JavaScript's falsy values are `false`, `0`, `""`, `null`, `undefined`, and `NaN`. section 3.2.6

Render an element only when needed

In JSX, `{isVerified && <Checkmark />}` displays a checkmark when `isVerified` is truthy. The `&&` operator returns its first operand if that operand is falsy; otherwise, it returns the element. When the first operand is `false`, React renders nothing. section 3.2.6

Make numeric conditions explicit

For the cart, use `const hasItems = items.length > 0;` followed by `{hasItems && <button>Checkout</button>}`. Now an empty cart makes the expression return `false`, which React renders as nothing. The distinction matters: both 0 and `false` are falsy, but React displays 0. section 3.4.3

Table 3.2 React rendering different types (view table figure)

Type

Output

"string"

"string"

""

""

3.4

"3.4"

0

"0"

NaN

"NaN"

Number.POSITIVE_INFINITY

"Infinity"

Number.NEGATIVE_INFINITY

"-Infinity"

true

"true"

false

""

undefined

""

null

""

Compare how React displays primitive values: `false`, `null`, and `undefined` appear as empty strings, while 0 appears as `"0"` and `NaN` as `"NaN"`. section 3.4.3

How React Quickly, Second Edition covers it

How deep it goes
Defines truthiness through six falsy values and works through short-circuit results and their rendering, without exploring coercion internals.
Examples
Contrasts a verified-user checkmark with a shopping-cart button whose numeric condition accidentally displays 0.
What it assumes
Assumes familiarity with simple JavaScript conditions and JSX expressions while defining truthy and falsy values directly.
What you can do after
Diagnose/debug with it: replace numeric JSX conditions with Boolean comparisons to prevent stray 0 output.
How it connects
Connects truthiness to JSX conditional rendering, logical AND, short-circuit evaluation, and rendering primitive values.

Also explained in

Compare how 6 books explain truthiness →

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.