JavaScript Callbacks: How Array.filter Selects Items
In this article
JavaScript callbacks are functions passed into other functions, and Array.filter() uses a callback to test each item in an array, returning a new array containing only the items for which the callback returns true. The callback receives the current element, its index, and the original array, and its return value determines whether that element is kept.
What Is a Callback Function?
A callback is simply a function that is passed as an argument to another function and is executed later, usually after some operation completes. In JavaScript, functions are “first-class citizens,” meaning they can be assigned to variables, stored in objects, and passed around like any other value. This makes callbacks a core pattern for asynchronous code (like event handlers or network requests) and for array methods like map, reduce, and filter.
For example, the forEach method takes a callback and runs it for each element. The callback itself doesn’t need a name; it can be written inline as an anonymous function or as an arrow function. The key idea is that the method controls when and how the callback is invoked.
How Array.filter Works Internally
The filter() method creates a new array with all elements that pass a test provided by a callback. Internally, it iterates over each element of the original array, calls the callback with three arguments:
- element – the current item’s value
- index – the position of the current item (0-based)
- array – the original array being filtered
If the callback returns a truthy value (like true, a non-zero number, or a non-empty string), the element is added to the new array. If it returns a falsy value (false, 0, null, undefined, NaN, or ''), the element is skipped. The original array is never modified; filter() always returns a new array, even if no elements pass.
Here’s a simple example:
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]The arrow function num => num % 2 === 0 is the callback. For each element, it checks if the remainder when divided by 2 is 0. Only the numbers that satisfy this condition are included in the result.
Writing a Filter Callback: Return True or False
The most important rule is that your callback must return a boolean (or a truthy/falsy value). If you forget to return, the callback returns undefined, which is falsy, so no items will be kept. This is a common beginner mistake.
Here are a few examples of valid callbacks:
item => item.price > 100– keeps items with a price greater than 100item => item.name.includes('a')– keeps items whose name contains the letter “a”(item, index) => index % 2 === 0– keeps items at even indices
You can also use a named function as the callback. For instance:
function isLongWord(word) {
return word.length > 5;
}
const words = ['apple', 'banana', 'cherry', 'date'];
const longWords = words.filter(isLongWord);
console.log(longWords); // ['banana', 'cherry']Notice that you pass the function reference isLongWord, not isLongWord(). The parentheses would call the function immediately and pass its result, which is not what you want.
Common Pitfalls and Misconceptions
One widespread misunderstanding is that filter() modifies the original array. It does not. If you need the original array to change, you must reassign it: arr = arr.filter(...).
Another issue is using filter() to remove items by mutating the array inside the callback. That can lead to unexpected behavior because the array is being changed while it is being iterated. Always treat the callback as a pure test: it should only read values, not modify the array.
Also, be careful with the callback’s return value. If you write item => { item.active } (with curly braces), it returns undefined because the braces create a block, not an object. You need parentheses for an object literal: item => ({ active: item.active }), or simply return the property directly.
Finally, note that filter() skips empty slots in sparse arrays. For example, [1, , 3].filter(x => true) returns [1, 3] – the hole is not preserved.
Filter vs. Other Array Methods
It helps to understand how filter() differs from other common array methods:
- map() – transforms every element and returns a new array of the same length.
- reduce() – accumulates a single value from all elements.
- find() – returns the first element that passes the test, or
undefined. - some() – returns
trueif at least one element passes the test. - every() – returns
trueif all elements pass the test.
Use filter() when you want a subset of the original array. Use map() when you want to change each element. Use reduce() when you need to combine all elements into a single result. Often you’ll chain them: arr.filter(...).map(...).
Performance and When to Use Filter
In terms of performance, filter() runs in O(n) time – it visits every element once. For most everyday arrays (hundreds or thousands of items), this is perfectly fine. If you’re dealing with very large datasets (millions of items), you might consider using a regular loop or a more specialized data structure, but the overhead of filter() is negligible for typical web applications.
One thing to keep in mind: filter() creates a new array, which uses extra memory. If you’re filtering a massive array and only need to process the results once, you could use a for loop and avoid the extra allocation. However, the readability and expressiveness of filter() usually outweigh this minor cost.
Real-World Examples
Filtering is used everywhere in JavaScript. Here are a few practical scenarios:
- Filtering user input: Remove empty strings from a list of form values.
- Filtering API data: Keep only products that are in stock.
- Filtering by date: Select events that occur after today.
- Filtering by nested properties:
users.filter(user => user.address.city === 'Paris')
You can also combine filter() with other methods. For example, to get the total price of in-stock items:
const total = products
.filter(p => p.inStock)
.reduce((sum, p) => sum + p.price, 0);This first filters to only in-stock items, then sums their prices.
Frequently Asked Questions
Does filter() change the original array?
No. filter() returns a new array and leaves the original untouched. If you want to update the original variable, you need to assign the result back: arr = arr.filter(...).
What happens if the callback returns a truthy value that isn’t true?
It works the same as returning true. JavaScript uses truthiness, so values like 1, 'hello', or {} are considered “truthy” and the element is kept. Only falsy values (false, 0, '', null, undefined, NaN) cause the element to be excluded.
Can I use an async function as a filter callback?
No. filter() does not wait for promises. If you use an async callback, it returns a Promise, which is always truthy, so every element will be kept. For asynchronous filtering, you need to first resolve all items (e.g., with Promise.all) and then filter the results.
How do I filter an array of objects by a property?
Access the property inside the callback. For example, to keep objects where age is greater than 18: people.filter(person => person.age > 18). You can also chain multiple conditions: person.age > 18 && person.active.
Is filter() available in all browsers?
Yes, Array.prototype.filter() is part of ECMAScript 5 (2009) and is supported in all modern browsers, including Internet Explorer 9 and later. For very old environments, you can use a polyfill, but it’s rarely needed today.
What’s the difference between filter() and find()?
filter() returns an array of all matching elements (or an empty array if none match). find() returns only the first matching element, or undefined if no match is found. Use find() when you expect only one result.