liveBook · Manning

Truthiness

As explained in Pro Angular 16

A truthy value is a JavaScript value that evaluates as true in a Boolean context.

A value is truthy when JavaScript treats it as true in a Boolean context. Only false, 0, the empty string (""), null, undefined, and NaN are falsy; every other value is truthy. That includes the string "false". When a condition is meant to answer a yes-or-no question, prefer an expression that produces the Boolean value true or false. section 3.4.7

A fallback that replaces zero

Given `let val3: number | undefined = 0`, the expression `val3 || 100` produces 100: `||` treats zero as falsy. Use `val3 ?? 100` when the fallback should apply to null or undefined instead; its result is 0. section 3.4.7

Truthiness also controls Angular class membership. In `[class.bg-success]="(products()[1].price ?? 0) < 50"`, a truthy expression adds the class. The comparison produces a Boolean value, making the condition explicit. A special class binding manages just its named class without replacing existing classes such as `p-2`; an `ngClass` object map likewise includes a class when its property's value is truthy. section 11.4.1

Listing 11.12. Using the special class binding in the template.html file in the src/app folder
<div class="text-white">
    <div [class]="getClasses(0)">
        The first product is {{ products()[0].name }}
    </div>
    <div class="p-2"
        [class.bg-success]="(products()[1].price ?? 0) < 50"
        [class.bg-info]="(products()[1].price ?? 0) >= 50">
            The second product is {{products()[1].name}}
    </div>
</div>

The template shows two independent class conditions around a product price while retaining the existing padding class. section 11.4.1

How Pro Angular 16 covers it

How deep it goes
Defines the falsy values and works through operator and class-binding consequences, without descending into runtime internals.
Examples
Contrasts zero under `||` and `??`, then uses product-price comparisons to select Angular classes.
What it assumes
Introduces the falsy-value list alongside JavaScript operators, then assumes familiarity with expressions in Angular templates.
What you can do after
Apply it via JavaScript fallback operators and Angular class bindings without mistaking zero or the string "false" for a Boolean result.
How it connects
Links Boolean expressions to logical OR, nullish coalescing, Angular class bindings, and ngClass.

Also explained in

Compare how 6 books explain truthiness →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.