HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Array Iteration

Array iteration methods operate on every item in an array. Instead of using traditional for loops, these methods provide a more readable and functional way to process data collections.


1. forEach()

The forEach() method calls a function (callback) once for each array element.

const numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);

function myFunction(value, index, array) {
  console.log(value);
}

2. map()

The map() method creates a new array by performing a function on each array element. It does not change the original array.

const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(x => x * 2); 
// Result: [90, 8, 18, 32, 50]

3. filter()

The filter() method creates a new array with array elements that pass a "test".

const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(value => value > 18);
// Result: [45, 25]

4. reduce()

The reduce() method runs a function on each array element to produce (reduce it to) a single value. A common use is finding the sum of all numbers.

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce((total, value) => total + value);
// Result: 99

5. every() and some()

  • every(): Checks if all array values pass a test.
  • some(): Checks if some array values pass a test.
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(x => x > 18); // false
let someOver18 = numbers.some(x => x > 18);   // true
Note: Most iteration methods take a callback function that receives three arguments: value, index, and the array itself.

Key Points to Remember

  • Iteration methods are cleaner and more modern than for loops
  • map() and filter() return new arrays
  • forEach() does not return anything (used for side effects)
  • reduce() turns an array into a single result (sum, average, object, etc.)
  • Arrow functions make iteration code much shorter and easier to read
  • None of these methods change the original array (they are non-mutating)