filter(Boolean) Removes Falsy Values

filter(Boolean) drops every falsy entry, including 0 and empty strings; an explicit predicate keeps legal zeros and reads clearly at review time.

JavascriptData Integrity

Code

javascriptsnippet
13 lines
const raw = ["ready", "", 0, "draft", null, undefined, NaN, false, 42];

// filter(Boolean) 用真值判断:falsy 值 0、""、null、undefined、NaN、false 全部被移除
const truthy = raw.filter(Boolean);
console.log(`truthy: ${JSON.stringify(truthy)}`);

// 显式谓词更可读,也能保留合法的 0
const keepZero = raw.filter((value) => value !== null && value !== undefined && value !== "");
console.log(`keep zero: ${JSON.stringify(keepZero)}`);

const numbers = raw.filter(Number.isFinite);
console.log(`numbers: ${JSON.stringify(numbers)}`);

Output

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

truthy: ["ready","draft",42]
keep zero: ["ready",0,"draft",null,false,42]
numbers: [0,42]

How it works

The demo data lives in module-level bindings: raw, truthy, keepZero, numbers.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

Running the file prints labeled results such as truthy: $, keep zero: $, numbers: $ — each operation’s effect is visible in the output.

Key statements

const keepZero = raw.filter((value) => value !== null && value !== undefined && value !== "");

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `raw`, `truthy`, `keepZero`.