JavaScript ES2024 ·
✓ verified by execution on 2026-08-12T16:30:47.465Z
Introduction
The filter() method of Array instances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
filter() as a sieve: each element is tested by the predicate, the ones that fail are dropped, and the survivors form a new array — the original is untouched.
Wrong Belief: filter() modifies the original array in place.
Reality: filter() creates and returns a new shallow copy array; the original array is left unchanged.
Wrong Belief: filter() requires returning true or false explicitly.
Reality: filter() coerces the return value to a boolean. Any truthy value keeps the element, and any falsy value drops it.
Wrong Belief: filter() will include empty slots from a sparse array.
Reality: filter() skips empty slots entirely; they are never passed to the callback.
Wrong Belief: An arrow function with curly braces returns a value implicitly.
Reality: If you use curly braces {} in an arrow function, you must explicitly use the ‘return’ keyword, otherwise it returns undefined (which is falsy, so all elements are dropped).
Edge Cases
Filtering an array where every element fails the test returns a new empty array [] rather than null or undefined.
When filtering an array of objects, the new array contains references to the same objects, not deep copies.
Check yourself
What does the filter() method return?
Reveal answer
A new array containing only elements that pass the test — filter() creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test.
Does filter() mutate the original array?
Reveal answer
No, it returns a new array — filter() is a non-mutating method that creates a shallow copy.
What happens if you use an arrow function with {} but forget the return statement in filter()?
Reveal answer
It returns undefined (falsy), so all elements are dropped — Arrow functions with block bodies {} require an explicit return statement. Without it, they return undefined, which is coerced to false.
Challenges
Challenge 1 +100 XP
Use `filter()` to return a new array containing only the even numbers from the `numbers` array.
javascript
Test 1 — expects "[ 10, 20, 30 ]"
Need a hint? (−25% XP)
An even number has a remainder of 0 when divided by 2 (n % 2 === 0).