Skip to main content

Command Palette

Search for a command to run...

πŸ”Ž Understanding .filter(Boolean) in JavaScript

Published
β€’2 min read
πŸ”Ž Understanding .filter(Boolean) in JavaScript
R

πŸŽ“ B.Tech CSE | πŸ‘¨β€πŸ’» Learning DSA & C++ | πŸš€ Building projects & writing what I learn | πŸ“š Currently solving LeetCode & exploring Git/GitHub


πŸ”Ή What is Boolean?

Boolean is a built-in JavaScript function that converts any value into either:

  • true βœ… (if the value is truthy)

  • false ❌ (if the value is falsy)

It basically answers: β€œIs this value truthy or falsy?”

Examples:

Boolean(1);        // true
Boolean(0);        // false
Boolean("hello");  // true
Boolean("");       // false
Boolean(null);     // false
Boolean(undefined);// false

πŸ”Ή Why use Boolean in .filter()?

Normally, .filter() needs a function that decides whether to keep an item (true) or remove it (false).

When you write:

array.filter(Boolean)
  • Each element is passed to Boolean().

  • If Boolean(item) returns true, it stays in the array.

  • If it returns false, it gets removed.

πŸ‘‰ This is a shortcut for removing empty, null, or invalid values without writing long conditions.

Equivalent to:

array.filter(item => Boolean(item));

or

array.filter(item => !!item);

πŸ”Ή How does it work with an example?

Suppose you want to display a candidate’s location (city + state) but avoid blank commas if one is missing:

<TableCell className="text-right">
  {[candidate.location_city, candidate.location_state].filter(Boolean).join(", ")}
</TableCell>

Step 1: Create an array

["Delhi", ""] // (if state is missing)

Step 2: Apply .filter(Boolean)

  • "Delhi" β†’ Boolean("Delhi") = true β†’ βœ… keep it

  • "" β†’ Boolean("") = false β†’ ❌ remove it

Result:

["Delhi"]

Step 3: Join values

["Delhi"].join(", ")  // "Delhi"

βœ… Final Output β†’ "Delhi" (with no trailing comma)


πŸ”Ή Which values are falsy?

These will be automatically removed:

  • false

  • 0

  • "" (empty string)

  • null

  • undefined

  • NaN


πŸ”Ή Which values are truthy?

Everything else:

  • "hello" (non-empty string)

  • " " (string with a space)

  • 123, -1

  • [] (empty array)

  • {} (empty object)

  • function(){}

  • "false" (string β†’ truthy even if it looks like false)


βœ… Why is this useful?

  • Removes unnecessary checks like:

      if (value !== "" && value !== null && value !== undefined)
    
  • Makes code cleaner, shorter, and safer.

  • Especially handy for joining values (like city/state), cleaning arrays, or filtering form inputs.


πŸ“ In summary:

Using .filter(Boolean) is a smart and concise way to remove falsy values ("", null, undefined, 0, NaN, false) from arrays.

In your candidate location example, it ensures only valid values (city/state) are displayed, without leaving blank spaces or extra commas.


More from this blog

I

Internship Learnings

17 posts