JS Array Iteration

JavaScript Array Iteration Methods

Array iteration methods operate on every element of an array, making it easy to loop through arrays and perform actions without writing a manual for loop. These methods are a cornerstone of modern, functional JavaScript.


1. The forEach() Method

The forEach() method calls a function (a callback function) once for each array element. It is a simple and readable way to iterate over an array.

forEach() Example

const fruits = ["apple", "orange", "cherry"];

fruits.forEach(myFunction);

function myFunction(item, index, arr) { console.log("Item at index " + index + " is " + item); }

Note: The callback function can accept three arguments: the item value, the item index, and the array itself.


2. The map() Method

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

map() Example

const numbers1 = [4, 9, 16, 25];

// Create a new array with the square root of each number const numbers2 = numbers1.map(Math.sqrt);

console.log(numbers2); // [2, 3, 4, 5]


3. The filter() Method

The filter() method creates a new array with all elements that pass a test (provided as a function).

filter() Example

const ages = [32, 33, 16, 40];

// Create a new array with only the adults const adults = ages.filter(checkAdult);

function checkAdult(age) { return age >= 18; }

console.log(adults); // [32, 33, 40]


4. The reduce() Method

The reduce() method runs a function on each array element to produce (or reduce it to) a single value. It works from left-to-right in the array.

reduce() Example

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

// Get the sum of all numbers const sum = numbers.reduce(myFunction);

function myFunction(total, value) { return total + value; }

console.log(sum); // 10


5. every() and some()

every() and some() Example

const numbers = [4, 9, 16, 25, 29];

let allOver18 = numbers.every(value => value > 18); let someOver18 = numbers.some(value => value > 18);

console.log(allOver18); // false console.log(someOver18); // true


Exercise

?

Which method creates a new array by transforming every element in an existing array?