๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Array Iteration

Array iteration runs code once for each item in an array. Each iteration method handles the items in its own way.

Visit each item

forEach hands each item and its index to the callback. The callback logs both values.

const fruits = ["Apple", "Pear"];
fruits.forEach((fruit, index) => console.log(index, fruit));

Build a new array

map returns a new array of doubled numbers. The original array stays the same.

const nums = [1, 2, 3];
const doubled = nums.map(num => num * 2);
console.log(doubled);
console.log(nums);

Keep passing items

filter tests each score against the mark. Scores over 50 go into the new array.

const scores = [35, 72, 58, 90];
const high = scores.filter(score => score > 50);
console.log(high);

Example

const numbers = [2, 5, 8, 11];
const tripled = numbers.map(num => num * 3);
console.log(tripled);
const big = tripled.filter(num => num > 20);
console.log(big);
big.forEach(num => console.log(num));

Key points

  • A callback is a function handed to a method.
  • The method calls the callback once for each item.
  • forEach runs its callback for every item.
  • map builds a new array from changed items.
  • map leaves the original array unchanged.
  • filter keeps only the items that pass a test.

In this example, map triples every number into a new array. filter then keeps the values over 20. forEach logs each kept value on its own line.

Note

reduce folds all items into one value, and it gets a fuller look later.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does the map method return?