JavaScript often surprises us with how much we can do using very little code.
One such powerful and commonly used trick is:
const arr = ["", null, undefined, false, 0, 1, 2];const result = arr.filter(Boolean);console.log(result);
✅ Output
[1, 2]
But why does this happen?
Let’s break it down in a simple and clear way.
What Does filter(Boolean) Mean?
The filter() method creates a new array by keeping only the elements that satisfy a condition.
This line:
arr.filter(Boolean)
is actually shorthand for:
arr.filter(value => Boolean(value))
So every element in the array is passed into the Boolean() function.
How Boolean() Works in JavaScript
The Boolean() function converts any value into either true or false.
❌ Falsy Values
These values always return false:
""(empty string)nullundefinedfalse0NaN
✅ Truthy Values
Everything else is considered true, including:
12"hello"[]{}
🔎 Step-by-Step Execution
| Value | Boolean(value) | Included? |
|---|---|---|
"" | false | ❌ |
null | false | ❌ |
undefined | false | ❌ |
false | false | ❌ |
0 | false | ❌ |
1 | true | ✅ |
2 | true | ✅ |
Only truthy values survive the filter.
Final Result
[1, 2]
✨ Why Developers Love This Pattern
Using filter(Boolean):
- Removes unwanted falsy values
- Makes code shorter and cleaner
- Improves readability once understood
Instead of writing:
arr.filter(value => value !== null && value !== undefined && value !== "")
You can simply write:
arr.filter(Boolean)
⚠️ Important Thing to Remember
This method removes all falsy values, including 0 and false.
So do not use it if 0 or false are valid values in your data.
When to Use filter(Boolean)
✅ Cleaning API responses
✅ Removing empty values from arrays
✅ Simplifying data before rendering
❌ When 0 or false are meaningful values
🧠 Interview One-Liner
filter(Boolean)is a concise way to remove all falsy values from an array in JavaScript.
📌 Final Thought
Sometimes, one line of JavaScript can replace multiple lines of code —
but only if you truly understand why it works.
Happy coding 🚀
If this Post helps you don’t forget to like and subscribe !!