liveBook · Manning

Truthiness

As explained in Essential TypeScript 5, Third Edition

A falsy value is a JavaScript value that is coerced to false in a boolean context.

Truthiness describes how JavaScript coerces values to booleans in boolean contexts. The falsy values are false, null, undefined, 0, "", and NaN; other values are treated as true. section 3.3.2

Use truthiness carefully when supplying fallback values with the logical OR operator:

  • firstCity || "London" uses London when firstCity is undefined or null. section 3.3.2
  • The same expression also replaces valid falsy values such as 0, "", and NaN, which can produce unexpected results. section 3.3.2
  • Use the nullish coalescing operator when only null and undefined should trigger the fallback. section 3.3.2

Preserving a zero tax rate

With taxRate || 10, both an undefined rate and a zero rate produce 10%. Replacing it with taxRate ?? 10 produces 10% for undefined and 0% for zero. section 3.3.2

...
let hatPrice = 100;
console.log(`Hat price: ${hatPrice}`);
let bootsPrice = "100";
console.log(`Boots price: ${bootsPrice}`);

if (hatPrice == bootsPrice) {
...

Browse the surrounding coercion examples before comparing fallback behavior and strict equality. section 3.3.2

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Defines the falsy set and demonstrates OR and nullish fallback behavior, but does not detail coercion internals.
Examples
Contrasts undefined and zero tax rates, and uses an undefined city value with an OR fallback.
What it assumes
Assumes familiarity with JavaScript values, variables, operators, and undefined variables.
What you can do after
Apply truthiness by selecting OR or nullish coalescing according to whether zero and empty strings are valid values.
How it connects
Connects truthiness with type coercion, logical OR, nullish coalescing, and boolean contexts.

Also explained in

Compare how 6 books explain truthiness →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.