JavaScript Array filter() Method: Syntax & Examples
Direct Answer & Overview
The JavaScript Array filter() method creates a shallow copy of an array containing only the elements that pass the test implemented by the provided predicate callback function. Elements that evaluate to truthy are retained, while others are omitted.
JavaScript Source Code
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers);How does this JavaScript code work?
Array.prototype.filter() iterates over every item in an array, invoking a predicate function that must evaluate to either truthy or falsy. If the callback returns truthy, the current item is copied into the output array; otherwise, it is skipped. The original array is never modified. If no items satisfy the predicate condition, filter() returns an empty array rather than null or undefined.
What is the expected terminal output?
Executing this code in JS CodeLab produces the following stdout sequence in the developer console:
[2,4,6]Common mistakes to avoid
- !Returning the item itself instead of a boolean comparison expression, causing falsy values like 0 or '' to be accidentally excluded.
- !Expecting filter() to return a single element; use Array.prototype.find() if you only want the first matching item.
- !Mutating array items inside the predicate callback function.
- !Expecting filter to alter the original array in place; filter returns a new array that must be stored in a variable.
Frequently Asked Questions
What does Array filter() return if no items match?
If no elements pass the test condition, filter() returns a new, empty array ([]), never null or undefined.
How does Array filter() differ from Array find()?
The filter() method iterates the entire array and returns a new array with all matching elements. The find() method stops at the first match and returns the element itself (or undefined).
Does filter() skip empty slots in sparse arrays?
Yes. Array.prototype.filter() does not invoke the predicate callback for index positions that have never been assigned or were deleted.
Comprehensive Tutorial
Want an in-depth understanding of this topic?
Read our complete, interactive tutorial covering memory management, edge cases, and best practices.
Read the full map vs-foreach tutorial →