JavaScript Array Iteration Methods

JavaScript provides powerful iteration methods that let you loop through arrays, transform data, filter elements, and reduce arrays to single values. These methods are the backbone of functional programming in JavaScript.

forEach()

forEach() executes a provided function once for each array element. It does not return a new array and cannot be chained. Use it for side effects like logging.

forEach()
const fruits = ["Apple", "Banana", "Cherry"];

// Basic forEach
fruits.forEach(function(item, index) {
  console.log(`${index}: ${item}`);
});

// Arrow function
fruits.forEach((item, index, array) => {
  console.log(`${item} is at position ${index} of ${array.length}`);
});

map()

map() creates a new array by calling a function on every element. It returns a new array of the same length with transformed values. The original array is not modified.

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

// Double each number
const doubled = numbers.map(n => n * 2);
console.log("Doubled:", doubled);

// Extract property from objects
const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 }
];
const names = users.map(u => u.name);
console.log("Names:", names);

// Transform with index
const indexed = numbers.map((n, i) => `Item ${i}: ${n}`);
console.log("Indexed:", indexed);

filter()

filter() creates a new array with all elements that pass a test. The callback function should return true to keep the element or false to exclude it.

filter()
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Even numbers
const evens = numbers.filter(n => n % 2 === 0);
console.log("Evens:", evens);

// Filter objects
const products = [
  { name: "Laptop", price: 999 },
  { name: "Phone", price: 699 },
  { name: "Tablet", price: 499 },
  { name: "Watch", price: 299 }
];
const expensive = products.filter(p => p.price > 500);
console.log("Expensive:", expensive.map(p => p.name));

// Remove falsy values
const mixed = [0, "hello", "", null, 42, undefined, "world"];
const truthy = mixed.filter(Boolean);
console.log("Truthy:", truthy);

reduce()

reduce() executes a reducer function on each element, passing the result from one call to the next, reducing the array to a single value. It takes a callback and an optional initial value.

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

// Sum all numbers
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log("Sum:", sum);

// Find maximum
const max = numbers.reduce((a, b) => a > b ? a : b);
console.log("Max:", max);

// Count occurrences
const fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const counts = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});
console.log("Counts:", counts);

// Flatten array
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
console.log("Flattened:", flat);
📝 Note: Always provide an initial value for reduce(). Without it, the first element is used as the initial value, which can cause errors on empty arrays and unexpected behavior with objects.

every() and some()

every() returns true if ALL elements pass the test. some() returns true if ANY element passes the test. Both short-circuit: every() stops at the first false, some() stops at the first true.

every() and some()
const numbers = [2, 4, 6, 8, 10];

// every - all elements pass the test?
console.log("All even:", numbers.every(n => n % 2 === 0));
console.log("All > 5:", numbers.every(n => n > 5));

// some - at least one passes?
console.log("Some > 5:", numbers.some(n => n > 5));
console.log("Some > 20:", numbers.some(n => n > 20));

// Practical: validate form fields
const fields = [
  { name: "email", value: "a@b.com" },
  { name: "name", value: "" },
  { name: "age", value: "25" }
];
const allFilled = fields.every(f => f.value.length > 0);
console.log("All filled:", allFilled);
const hasEmpty = fields.some(f => f.value.length === 0);
console.log("Has empty:", hasEmpty);

Chaining Methods

Since map(), filter(), and other methods return arrays, you can chain them together to create powerful data transformations in a readable way.

Chaining Methods
const products = [
  { name: "Laptop", price: 999, inStock: true },
  { name: "Phone", price: 699, inStock: false },
  { name: "Tablet", price: 499, inStock: true },
  { name: "Watch", price: 299, inStock: true },
  { name: "Camera", price: 899, inStock: true }
];

// Filter, transform, and reduce in one chain
const totalInStock = products
  .filter(p => p.inStock)
  .map(p => p.price)
  .reduce((sum, price) => sum + price, 0);
console.log("Total in-stock value:", totalInStock);

// Get sorted names of affordable items
const affordable = products
  .filter(p => p.price < 700 && p.inStock)
  .map(p => p.name)
  .sort();
console.log("Affordable & in stock:", affordable);
MethodReturnsPurpose
forEach()undefinedExecute side effects
map()New arrayTransform each element
filter()New arrayKeep elements that pass test
reduce()Single valueAccumulate into one value
every()BooleanTest if ALL pass
some()BooleanTest if ANY passes
Exercise:
What does [1,2,3].map(x => x * 2).filter(x => x > 3) return?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.