Member-only story

Top 3 Ways to Iterate a JavaScript Array using forEach, map and filter methods

Marika Lam
2 min readSep 8, 2022

--

1. JavaScript Array forEach()

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

const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value + "<br>";
}

2. JavaScript Array map()

The map() method creates a new array by performing a function on each array element.

The map() method does not execute the function for array elements without values.

The map() method does not change the original array.

const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2;
}

3. JavaScript Array filter()

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

const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);
function myFunction(value, index, array) {
return value > 18;
}

--

--

No responses yet