Mastering map(), filter(), reduce(), and forEach() in JavaScript
JavaScript provides powerful methods for processing arrays. These methods — map(), filter(), reduce(), and forEach() — are higher-order functions. That means they take a function as an argument and apply it to each element in an array.
forEach()
Purpose:
Executes a provided function once for each array element.
Syntax:
array.forEach((element, index, array) => {
// your code here
});Parameters:
element: The current element.index(optional): Index of the current element.array(optional): The entire array.
Key Features:
- Doesn’t return anything (
undefined). - Used for side effects, like logging or DOM updates.
Example:
const fruits = ['apple', 'banana', 'mango'];
fruits.forEach((fruit, index) => {
console.log(`${index + 1}: ${fruit}`);
});2. map()
Purpose:
Creates a new array populated with the results of calling a function on every element.
Syntax:
const newArray = array.map((element, index, array) => {
return modifiedElement;
});Key Features:
- Always returns a new array.
- Original array is not modified.
- Useful for transforming data.
Example:
const nums = [1, 2, 3];
const squared = nums.map(n => n * n);
console.log(squared); // [1, 4, 9]3. filter()
Get shubham’s stories in your inbox
Join Medium for free to get updates from this writer.
Purpose:
Creates a new array with only the elements that pass a test (i.e., function returns true).
Syntax:
const filteredArray = array.filter((element, index, array) => {
return condition;
});Key Features:
- Returns a subset of the original array.
- Does not mutate the original array.
4. reduce()
Purpose:
Reduces the array to a single value by applying a reducer function.
Syntax:
const result = array.reduce((accumulator, currentValue, index, array) => {
return newAccumulator;
}, initialValue);Key Features:
- Great for totals, averages, and complex transformations.
- Returns any type of value (not just arrays).
- Needs an initial value for best practice.
Example: Sum of numbers
const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, val) => acc + val, 0);
console.log(sum); // 10Example: Create an object from an array
const fruits = ['apple', 'banana', 'apple'];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(count); // { apple: 2, banana: 1 }Advanced Tips:
map().filter() can be chained.
const result = arr.map(x => x * 2).filter(x => x > 10);Use reduce() for flattening arrays:
const nested = [[1,2], [3,4]];
const flat = nested.reduce((acc, val) => acc.concat(val), []);








