liveBook · Manning

Truthiness

As explained in JavaScript in Depth

The language process that converts a value to a boolean according to the language's truthiness and falsiness rules.

A check such as `if (!transactionId)` can double-charge a customer when valid identifier `0` is mistaken for absence. Truthiness is JavaScript’s implicit conversion of any value to a boolean in a conditional or logical context: falsy values behave like `false`, while all others behave like `true`. section 4.0 section 4.2.1

Treat these values as falsy:

  • `undefined`, `null`, `false`, `0`, `-0`, `0n`, `-0n`, `NaN`, and `''`. section 4.2.1
  • Treat every other value as truthy, including `'0'`, `'false'`, `[]`, and `{}`. section 4.2.1
  • Remember that truthiness differs from numeric or equality coercion: `[]` is truthy in a condition but can compare equal to `false` through chained conversions. section 4.4.3

When absence is not falsiness

A discount function using `if (!code)` treats both `''` and `0` as missing, although either might be meaningful input. Check the intended absence explicitly, for example with `code == null` when only `null` and `undefined` should count as missing. section 4.2.1

!!'hello'  #A
!![]  #A
!!null  #B
!!''  #B

Use double negation to observe truthiness directly: the first `!` converts and inverts, while the second restores the boolean result. section 4.2.2

How JavaScript in Depth covers it

How deep it goes
Defines every falsy value, contrasts truthiness with chained coercion, and briefly connects primitive handling to V8 pointer tagging.
Examples
Uses payment identifiers, discount codes, empty arrays, double negation, and defaulting expressions to expose surprising behavior.
What you can do after
Apply via JavaScript conditionals and logical operators while distinguishing meaningful falsy values from actual absence.
How it connects
Connects truthiness to type coercion, boolean operators, short-circuit evaluation, nullish coalescing, and equality.

Also explained in

Compare how 7 books explain truthiness →

Related concepts

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