π Understanding .filter(Boolean) in JavaScript

πΉ 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:
false0""(empty string)nullundefinedNaN
πΉ 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.

