JavaScript Iteration & Functional Array Methods — Complete Guide
Phase 4 — Arrays
Module 10.3 — Iteration & Functional Array Methods
Modern JavaScript encourages a functional programming style when working with arrays. Instead of manually looping through arrays using for loops, developers use higher-order array methods that are more readable, maintainable, and expressive.
These methods are heavily used in:
- React
- Next.js
- Vue
- Angular
- Node.js
- Express
- API data processing
- Data analytics
- Machine Learning preprocessing
This module covers the most important functional array methods used in professional development.
Overview
| Method | Purpose | Returns | Modifies Original |
|---|---|---|---|
forEach() | Execute a function for each element | undefined | ❌ |
map() | Transform each element | New Array | ❌ |
filter() | Select matching elements | New Array | ❌ |
reduce() | Reduce array to a single value | Any | ❌ |
reduceRight() | Reduce from right to left | Any | ❌ |
every() | Check if all elements satisfy a condition | Boolean | ❌ |
some() | Check if at least one element satisfies a condition | Boolean | ❌ |
forEach()
What is forEach()?
forEach() executes a callback function once for each array element.
Unlike map(), it does not create a new array.
Syntax
1array.forEach((element, index, array) => { 2 3});
Example
1const fruits = [ 2 "Apple", 3 "Banana", 4 "Orange" 5]; 6 7fruits.forEach((fruit) => { 8 console.log(fruit); 9});
Output
1Apple 2Banana 3Orange
Using Index
1fruits.forEach((fruit, index) => { 2 console.log(index, fruit); 3});
Output
10 Apple 21 Banana 32 Orange
Real-World Example
1const users = [ 2 3 { 4 name: "Ankit" 5 }, 6 7 { 8 name: "Rahul" 9 } 10 11]; 12 13users.forEach(user => { 14 15 console.log(user.name); 16 17});
When to Use
✅ Logging
✅ DOM Updates
✅ API Responses
✅ Side Effects
map()
What is map()?
map() creates a new array by transforming every element.
Syntax
1array.map(callback)
Example
1const numbers = [ 2 1, 3 2, 4 3 5]; 6 7const doubled = numbers.map(number => number * 2); 8 9console.log(doubled);
Output
1[2,4,6]
Original array
1[1,2,3]
Objects Example
1const users = [ 2 3 { 4 name: "Ankit" 5 }, 6 7 { 8 name: "Rahul" 9 } 10 11]; 12 13const names = users.map(user => user.name); 14 15console.log(names);
Output
1["Ankit","Rahul"]
Professional Example
1const products = [ 2 3 { 4 id:1, 5 price:100 6 }, 7 8 { 9 id:2, 10 price:250 11 } 12 13]; 14 15const prices = products.map(product => product.price);
filter()
What is filter()?
Returns a new array containing only elements that satisfy a condition.
Syntax
1array.filter(callback)
Example
1const numbers = [ 2 10, 3 20, 4 30, 5 40 6]; 7 8const result = numbers.filter(number => number > 20); 9 10console.log(result);
Output
1[30,40]
Filter Objects
1const users = [ 2 3 { 4 name:"Ankit", 5 active:true 6 }, 7 8 { 9 name:"Rahul", 10 active:false 11 } 12 13]; 14 15const activeUsers = users.filter( 16 user => user.active 17); 18 19console.log(activeUsers);
map() vs filter()
1numbers.map(x => x * 2);
Transforms every element.
1numbers.filter(x => x > 20);
Selects matching elements.
reduce()
What is reduce()?
Reduces an entire array into a single value.
Syntax
1array.reduce(callback, initialValue)
Sum Example
1const numbers = [ 2 10, 3 20, 4 30 5]; 6 7const total = numbers.reduce( 8 9 (sum, current) => sum + current, 10 11 0 12 13); 14 15console.log(total);
Output
160
Maximum Value
1const max = numbers.reduce( 2 3 (largest, current) => 4 5 largest > current 6 ? largest 7 : current 8 9);
Output
130
Count Objects
1const orders = [ 2 3 { 4 amount:200 5 }, 6 7 { 8 amount:500 9 }, 10 11 { 12 amount:300 13 } 14 15]; 16 17const revenue = orders.reduce( 18 19 (total, order) => total + order.amount, 20 21 0 22 23); 24 25console.log(revenue);
Output
11000
reduceRight()
Works exactly like reduce() but starts from the last element.
1const letters = [ 2 "A", 3 "B", 4 "C" 5]; 6 7const result = letters.reduceRight( 8 9 (text, letter) => text + letter, 10 11 "" 12 13); 14 15console.log(result);
Output
1CBA
every()
Checks whether all elements satisfy a condition.
Returns true or false.
1const marks = [ 2 80, 3 90, 4 75 5]; 6 7const passed = marks.every( 8 mark => mark >= 35 9); 10 11console.log(passed);
Output
1true
Another Example
1const ages = [ 2 18, 3 25, 4 16 5]; 6 7console.log( 8 9 ages.every(age => age >= 18) 10 11);
Output
1false
some()
Checks whether at least one element satisfies a condition.
1const ages = [ 2 18, 3 25, 4 16 5]; 6 7console.log( 8 9 ages.some(age => age < 18) 10 11);
Output
1true
Another Example
1const users = [ 2 3 { 4 admin:false 5 }, 6 7 { 8 admin:true 9 } 10 11]; 12 13console.log( 14 15 users.some(user => user.admin) 16 17);
Output
1true
every() vs some()
| Method | Returns True When |
|---|---|
every() | All elements match |
some() | At least one element matches |
Chaining Methods
One of the biggest advantages of functional programming.
1const numbers = [ 2 10, 3 20, 4 30, 5 40 6]; 7 8const result = numbers 9 10 .filter(number => number > 15) 11 12 .map(number => number * 2) 13 14 .reduce( 15 16 (sum, number) => sum + number, 17 18 0 19 20 ); 21 22console.log(result);
Output
1180
Practical Example — Student Result
1const students = [ 2 3 { 4 name:"Ankit", 5 marks:95 6 }, 7 8 { 9 name:"Rahul", 10 marks:60 11 }, 12 13 { 14 name:"Priya", 15 marks:85 16 } 17 18]; 19 20const toppers = students 21 22 .filter(student => student.marks >= 80) 23 24 .map(student => student.name); 25 26console.log(toppers);
Output
1["Ankit","Priya"]
Practical Example — Shopping Cart
1const cart = [ 2 3 { 4 name:"Laptop", 5 price:70000 6 }, 7 8 { 9 name:"Mouse", 10 price:800 11 }, 12 13 { 14 name:"Keyboard", 15 price:1500 16 } 17 18]; 19 20const total = cart.reduce( 21 22 (sum, item) => sum + item.price, 23 24 0 25 26); 27 28console.log(total);
Output
172300
Common Mistakes
Using map() Instead of forEach()
Wrong
1numbers.map(number => { 2 3 console.log(number); 4 5});
If you're not using the returned array, use forEach() instead.
Forgetting to Return
Wrong
1numbers.map(number => { 2 3 number * 2; 4 5});
Returns
1[undefined, undefined, undefined]
Correct
1numbers.map(number => number * 2);
Missing Initial Value in reduce()
1numbers.reduce( 2 3 (sum, number) => sum + number 4 5);
Works for non-empty arrays but can fail on empty arrays.
Better
1numbers.reduce( 2 3 (sum, number) => sum + number, 4 5 0 6 7);
Performance
| Method | Complexity |
|---|---|
forEach() | O(n) |
map() | O(n) |
filter() | O(n) |
reduce() | O(n) |
reduceRight() | O(n) |
every() | O(n)* |
some() | O(n)* |
every()andsome()can stop early when the result is determined, so they may finish before scanning the entire array.
Best Practices
- Use
forEach()for side effects such as logging or updating the DOM. - Use
map()to transform data without changing the original array. - Use
filter()to select a subset of elements. - Use
reduce()for sums, totals, grouping, counting, and data aggregation. - Use
every()for validation where all elements must meet a rule. - Use
some()to check if any element matches a condition. - Chain
filter(),map(), andreduce()to build clean, readable data-processing pipelines. - Avoid mutating objects inside
map()orfilter()callbacks.
Mini Project — Product Analytics Dashboard
index.html
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>Product Analytics</title> 6</head> 7<body> 8 9<h2>Product Analytics</h2> 10 11<div id="output"></div> 12 13<script src="script.js"></script> 14 15</body> 16</html>
script.js
1const products = [ 2 3 { 4 name:"Laptop", 5 price:70000, 6 stock:true 7 }, 8 9 { 10 name:"Mouse", 11 price:800, 12 stock:true 13 }, 14 15 { 16 name:"Keyboard", 17 price:1500, 18 stock:false 19 } 20 21]; 22 23const availableProducts = products.filter( 24 25 product => product.stock 26 27); 28 29const productNames = availableProducts.map( 30 31 product => product.name 32 33); 34 35const totalPrice = availableProducts.reduce( 36 37 (sum, product) => sum + product.price, 38 39 0 40 41); 42 43document.getElementById("output").innerHTML = ` 44<h3>Available Products</h3> 45<p>${productNames.join(", ")}</p> 46 47<h3>Total Value</h3> 48<p>₹${totalPrice}</p> 49`;
Interview Questions
Q1. What is the difference between map() and forEach()?
map()returns a new transformed array.forEach()returnsundefinedand is mainly used for side effects.
Q2. When should you use reduce()?
Use reduce() when you need to combine an array into a single value, such as a sum, average, grouped object, or lookup table.
Q3. What is the difference between every() and some()?
every()returnstrueonly if all elements satisfy the condition.some()returnstrueif at least one element satisfies the condition.
Q4. Can these methods modify the original array?
No. forEach(), map(), filter(), reduce(), reduceRight(), every(), and some() do not modify the array itself. However, if the array contains objects, mutating those objects inside the callback will affect the original data.
Summary
In this module, you learned:
- How
forEach()performs actions for each element. - How
map()transforms arrays into new arrays. - How
filter()selects elements based on conditions. - How
reduce()andreduceRight()aggregate arrays into single values. - How
every()validates that all elements satisfy a condition. - How
some()checks whether any element satisfies a condition. - How to chain functional array methods to build clean, declarative data-processing pipelines.
- Real-world applications of these methods in analytics dashboards, shopping carts, and data transformation workflows.
Next Module: Module 10.4 — Advanced Array Methods, where you'll learn
flat(),flatMap(),fill(),copyWithin(),keys(),values(), andentries()with real-world examples and performance considerations.