Falsy Values Collapse In Boolean Contexts

Seven values are falsy while empty arrays and objects are truthy, so filter(Boolean) compacts lists and || versus ?? treat missing defaults differently.

JavascriptData Integrity

Code

javascriptsnippet
30 lines
// Boolean contexts coerce any value to true or false.
// Only seven values are falsy; every other value is truthy.
const falsy = [
  ['false', false],
  ['0', 0],
  ['-0', -0],
  ['0n', 0n],
  ["''", ''],
  ['null', null],
  ['undefined', undefined],
  ['NaN', NaN],
];

for (const [label, value] of falsy) {
  console.log(`Boolean(${label}) = ${Boolean(value)}`);
}

// Surprises: empty arrays and objects are truthy despite looking empty.
console.log('Boolean([]) =', Boolean([]));
console.log('Boolean({}) =', Boolean({}));
console.log("Boolean('0') =", Boolean('0'));

// filter(Boolean) compacts falsy entries out of a list.
const mixed = [0, 'text', null, 42, '', undefined, NaN, false];
console.log('compacted:', mixed.filter(Boolean));

// || coerces for defaults, ?? only replaces null and undefined.
const input = '';
console.log("'' || 'anon' ->", input || 'anon');
console.log("'' ?? 'anon'  ->", input ?? 'anon');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

Boolean(false) = false
Boolean(0) = false
Boolean(-0) = false
Boolean(0n) = false
Boolean('') = false
Boolean(null) = false
Boolean(undefined) = false
Boolean(NaN) = false
Boolean([]) = true
Boolean({}) = true
Boolean('0') = true
compacted: [ 'text', 42 ]
'' || 'anon' -> anon
'' ?? 'anon'  ->

Inside the snippet

The cycling part of this snippet is for (const [label, value] of falsy).

Module-level bindings hold the data — falsy, mixed, input — with no function scope in between.

Caveats

  • No third-party code is loaded at any point while this runs.

Using it

Running the file prints labeled results such as Boolean($, Boolean([]) =, Boolean( — each operation’s effect is visible in the output.

Key statements

const mixed = [0, 'text', null, 42, '', undefined, NaN, false];
const input = '';

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. Its state lives in module-level bindings: `falsy`, `mixed`, `input`.