How to Chain Array Methods in JavaScript: Simple Guide
In JavaScript, you can chain array methods by calling one method after another on the same array, like
array.map().filter().reduce(). Each method returns a new array or value, allowing you to perform multiple steps in a single, readable line.Syntax
Chaining array methods means calling multiple methods one after another on an array. Each method processes the array and returns a new array or a value, which the next method uses.
array.method1().method2().method3()- Each
methodis an array function likemap,filter, orreduce. - The output of one method becomes the input for the next.
javascript
array.method1().method2().method3()
Example
This example shows chaining map, filter, and reduce to process numbers: first doubling them, then keeping only those greater than 10, and finally summing them.
javascript
const numbers = [3, 6, 9, 12]; const result = numbers .map(n => n * 2) // Double each number: [6, 12, 18, 24] .filter(n => n > 10) // Keep numbers > 10: [12, 18, 24] .reduce((sum, n) => sum + n, 0); // Sum them: 54 console.log(result);
Output
54
Common Pitfalls
Common mistakes when chaining array methods include:
- Not returning a value inside callbacks, causing
undefinedresults. - Using methods that do not return arrays (like
forEach) in chains, which breaks the chain. - Forgetting that
reducereturns a single value, so chaining after it may cause errors.
javascript
const arr = [1, 2, 3]; // Wrong: forEach returns undefined, breaks chain // arr.map(x => x * 2).forEach(x => console.log(x)).filter(x => x > 2); // Right: use filter after map, then forEach separately const filtered = arr.map(x => x * 2).filter(x => x > 2); filtered.forEach(x => console.log(x));
Output
4
6
Quick Reference
Here is a quick guide to common array methods used in chaining:
| Method | Description | Returns |
|---|---|---|
| map(callback) | Transforms each element | New array |
| filter(callback) | Keeps elements that pass test | New array |
| reduce(callback, initial) | Reduces array to single value | Single value |
| sort(callback) | Sorts elements | Sorted array |
| slice(start, end) | Extracts part of array | New array |
| forEach(callback) | Runs function on each element | undefined (no chaining) |
Key Takeaways
Chain array methods by calling one after another on the same array.
Each method should return a new array or value to continue the chain.
Avoid using methods like forEach in chains because they return undefined.
Use chaining to write clean and readable code for multiple array operations.
Remember reduce returns a single value, so it usually ends the chain.