Tools for working with arrays

INPUT · Slides

Doing the same thing to every item

01 / 06

The number ends up as the star

To work through every item of an array, for had you write this.

for (let i = 0; i < list.length; i++) { ... }

What you want is "do the same thing to all of them", but what is written is mostly the business of looking after the number i. Start at 0, keep it under length, do not forget the i++. All easy to get wrong.

Would it not be easier to say "to all of them" without the number appearing?

02 / 06

A function was a value

What is worth remembering is that a function is a value too. In the functions chapter, handing console.log a function without () showed function.

  • show … the function itself
  • show() … the result of running the function

That difference matters from here on. Leave the () off and you can carry the function about.

const show = (item) => {  console.log(item);};console.log(show);show("test");

Result

function
test

03 / 06

Hand a function to forEach

Write .forEach(function) after an array and it calls that function once for every item.

What you hand over is the function itself. So no (). There is nowhere for a number to be written.

const fruits = ["apple", "orange"];const show = (item) => {  console.log(item);};fruits.forEach(show);

Result

apple
orange

04 / 06

The items come in one at a time

When forEach calls the function, it hands that lap's item over as an argument. So write the function you hand over as one that catches a single argument.

The argument's name is up to you. item, n, whatever suggests the contents. It is called as many times as there are items.

const nums = [3, 5, 8];const twice = (n) => {  console.log(n * 2);};nums.forEach(twice);

Result

6
10
16

05 / 06

Hand it over with ( ) and it will not work

Here is a common stumble. Write forEach(show()) and you hand over the result of running show right there.

show does not return anything, so what goes over is undefined. forEach asked for a function and got something that is not one, so it errors.

An error is no problem. Deleting the () fixes it.

const nums = [1, 2];const show = (n) => {  console.log(n);};nums.forEach(show());

Result

undefined
error: undefined is not a function

06 / 06

The inside is written as always

Inside the { } of the function you hand over, nothing has changed. if, sums, template literals — all fine.

Work that needs the number (going backwards, stopping partway) suits for better. The same thing to every item means forEach — worth remembering.

Right — let us hand a function over.

const scores = [45, 80];const judge = (score) => {  if (score >= 60) {    console.log(`${score} pass`);  } else {    console.log(`${score} fail`);  }};scores.forEach(judge);

Result

45 fail
80 pass