DocsHub
Arrays

Array Iteration

Learn how to loop through and transform arrays using JavaScript's powerful built-in iteration methods.

Array Iteration

In the Loops section we used for and for...of to go through arrays. Those work fine — but JavaScript has a set of built-in iteration methods that are more powerful, more expressive, and what you will see in almost every real codebase.

Each method has a specific job — transforming, filtering, finding, checking. Instead of writing a loop and building the logic yourself, you just tell the method what to do with each item.

const numbers = [1, 2, 3, 4, 5];

// Loop version
const doubled = [];
for (const n of numbers) {
  doubled.push(n * 2);
}

// Iteration method version
const doubled = numbers.map(n => n * 2);

console.log(doubled); // [2, 4, 6, 8, 10]

Same result — the method version is shorter, cleaner, and tells you exactly what is happening.


forEach() — Do Something With Each Item

forEach() runs a function on every item in the array. It does not return anything — it is purely for side effects like logging or updating something external.

const fruits = ["apple", "mango", "banana"];

fruits.forEach(fruit => {
  console.log(fruit);
});
// apple
// mango
// banana

You also get the index as a second argument:

fruits.forEach((fruit, index) => {
  console.log(`${index + 1}. ${fruit}`);
});
// 1. apple
// 2. mango
// 3. banana

forEach vs for...of

Both loop through every item. The difference is that for...of supports break and continueforEach does not. Once forEach starts, it goes through every item no matter what.

// ✅ for...of — can break early
for (const fruit of fruits) {
  if (fruit === "mango") break;
  console.log(fruit);
}

// ❌ forEach — cannot break
fruits.forEach(fruit => {
  if (fruit === "mango") return; // return only skips this iteration
  console.log(fruit);
});

Use forEach when you want to do something with every item without exception. Use for...of when you might need to stop early.


map() — Transform Every Item

map() creates a new array by transforming every item using a function you provide. The original array is not modified.

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] — unchanged

The new array always has the same length as the original — every item is transformed, none are removed.

Real use — transforming data

const products = [
  { name: "Laptop", price: 120000 },
  { name: "Mouse", price: 1500 },
  { name: "Keyboard", price: 4500 },
];

// Add a discounted price to every product
const withDiscount = products.map(product => ({
  ...product,
  discountedPrice: product.price * 0.9
}));

console.log(withDiscount);
// [
//   { name: "Laptop", price: 120000, discountedPrice: 108000 },
//   { name: "Mouse", price: 1500, discountedPrice: 1350 },
//   { name: "Keyboard", price: 4500, discountedPrice: 4050 },
// ]

Real use — extracting a field

const users = [
  { name: "Ali", age: 22 },
  { name: "Sara", age: 25 },
  { name: "Zara", age: 20 },
];

const names = users.map(user => user.name);
console.log(names); // ["Ali", "Sara", "Zara"]

filter() — Keep Items That Pass a Test

filter() creates a new array containing only the items where the callback returns true. Items that return false are excluded.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];

const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6, 8]

The new array can be shorter than the original — only passing items are included.

Real use — filtering products

const products = [
  { name: "Laptop", price: 120000, inStock: true },
  { name: "Mouse", price: 1500, inStock: false },
  { name: "Keyboard", price: 4500, inStock: true },
  { name: "Monitor", price: 45000, inStock: false },
  { name: "Webcam", price: 8000, inStock: true },
];

const available = products.filter(product => product.inStock);
console.log(available.map(p => p.name));
// ["Laptop", "Keyboard", "Webcam"]
const students = ["Ali", "Sara", "Zara", "Salman", "Omar"];

const results = students.filter(name =>
  name.toLowerCase().startsWith("s")
);

console.log(results); // ["Sara", "Zara", "Salman"]

reduce() — Combine Into a Single Value

reduce() is the most powerful and most misunderstood iteration method. It goes through every item and accumulates them into a single value — a number, a string, an object, anything.

array.reduce((accumulator, currentItem) => {
  // return updated accumulator
}, initialValue);
  • accumulator — the running result, starts as initialValue
  • currentItem — the current item being processed
  • initialValue — the starting value of the accumulator

Summing numbers

const prices = [120, 450, 89, 300, 55];

const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 1014

Let's trace what happens step by step:

Start:        sum = 0
Iteration 1:  sum = 0   + 120 = 120
Iteration 2:  sum = 120 + 450 = 570
Iteration 3:  sum = 570 + 89  = 659
Iteration 4:  sum = 659 + 300 = 959
Iteration 5:  sum = 959 + 55  = 1014
Result: 1014

Finding the maximum value

const scores = [72, 95, 88, 61, 99, 74];

const highest = scores.reduce((max, score) => {
  return score > max ? score : max;
}, 0);

console.log(highest); // 99

Building an object from an array

const students = [
  { name: "Ali", grade: "A" },
  { name: "Sara", grade: "B" },
  { name: "Zara", grade: "A" },
];

const gradeMap = students.reduce((acc, student) => {
  acc[student.name] = student.grade;
  return acc;
}, {});

console.log(gradeMap);
// { Ali: "A", Sara: "B", Zara: "A" }

Always provide an initialValue as the second argument to reduce(). Skipping it uses the first array item as the initial value — which works sometimes but causes bugs with empty arrays and unexpected types.


find() — Get the First Matching Item

find() returns the first item that passes the test. If nothing matches, it returns undefined.

const users = [
  { id: 1, name: "Ali" },
  { id: 2, name: "Sara" },
  { id: 3, name: "Zara" },
];

const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: "Sara" }

const missing = users.find(u => u.id === 99);
console.log(missing); // undefined

Unlike filter() which returns all matches as an array, find() returns the actual item and stops as soon as it finds the first match.


findIndex() — Get the Index of the First Match

Same as find() but returns the index instead of the item. Returns -1 if not found.

const users = [
  { id: 1, name: "Ali" },
  { id: 2, name: "Sara" },
  { id: 3, name: "Zara" },
];

const index = users.findIndex(u => u.id === 2);
console.log(index); // 1

const missing = users.findIndex(u => u.id === 99);
console.log(missing); // -1

Useful when you need the position — for example to update or remove an item with splice().


some() — Check if At Least One Item Passes

some() returns true if at least one item passes the test. Stops as soon as it finds the first match.

const ages = [15, 22, 17, 30, 14];

const hasAdult = ages.some(age => age >= 18);
console.log(hasAdult); // true — 22 and 30 pass
const scores = [45, 38, 29, 41];

const anyPassing = scores.some(score => score >= 50);
console.log(anyPassing); // false — none passed

every() — Check if All Items Pass

every() returns true only if every single item passes the test. Stops as soon as it finds one that fails.

const ages = [22, 25, 30, 28];

const allAdults = ages.every(age => age >= 18);
console.log(allAdults); // true — all pass

const scores = [88, 92, 45, 76];

const allPassing = scores.every(score => score >= 50);
console.log(allPassing); // false — 45 fails

some vs every — quick comparison

const scores = [88, 92, 45, 76];

console.log(scores.some(s => s >= 50));  // true  — at least one passes
console.log(scores.every(s => s >= 50)); // false — not all pass

findLast() and findLastIndex() — Search From the End

These work exactly like find() and findIndex() but search from the end of the array instead of the beginning.

const numbers = [1, 2, 3, 4, 3, 5];

console.log(numbers.findLast(n => n === 3));      // 3 — last match
console.log(numbers.findLastIndex(n => n === 3)); // 4 — index of last match

Chaining Methods

Because map() and filter() return new arrays, you can chain them together — the output of one becomes the input of the next.

const students = [
  { name: "Ali",  score: 88, passed: true },
  { name: "Sara", score: 45, passed: false },
  { name: "Zara", score: 92, passed: true },
  { name: "Omar", score: 61, passed: true },
  { name: "Hassan", score: 30, passed: false },
];

const topStudents = students
  .filter(s => s.passed)           // keep only passing students
  .filter(s => s.score >= 80)      // keep only high scorers
  .map(s => s.name);               // extract just their names

console.log(topStudents); // ["Ali", "Zara"]
const orders = [
  { product: "Laptop", amount: 120000, status: "delivered" },
  { product: "Mouse",  amount: 1500,   status: "pending" },
  { product: "Monitor",amount: 45000,  status: "delivered" },
  { product: "Webcam", amount: 8000,   status: "pending" },
];

// Total revenue from delivered orders only
const revenue = orders
  .filter(order => order.status === "delivered")
  .reduce((total, order) => total + order.amount, 0);

console.log(`Revenue: Rs. ${revenue}`); // Revenue: Rs. 165000

Chaining makes your intent clear — each step does one thing, and the whole thing reads like a description of what you want.


Choosing the Right Method

const products = [120, 45, 89, 300, 55];
What you wantMethod
Do something with each itemforEach()
Transform every item into something newmap()
Keep only items that pass a testfilter()
Combine all items into one valuereduce()
Find the first item that matchesfind()
Find the index of the first matchfindIndex()
Check if at least one item passessome()
Check if every item passesevery()

Summary

  • forEach() — runs a function on every item, returns nothing
  • map() — transforms every item, returns a new array of same length
  • filter() — keeps items that pass, returns a new shorter array
  • reduce() — combines all items into one value
  • find() — returns the first matching item
  • findIndex() — returns the index of the first match
  • some() — returns true if at least one item passes
  • every() — returns true if all items pass
  • Methods can be chained — output of one feeds into the next
  • Always provide an initial value to reduce()

On this page