30 Days Of JavaScript

Day 10: Higher Order Functions Part 1

Lesson 1: forEach

Let's take 3 concepts and combine them:

  1. Arrays are really objects in JavaScript and so have other properties on them you can call, like .length
  2. Objects have functions stored as a property and you can call them like this myObject.myFunction()
  3. Functions can take other functions as inputs and they can be anonymous (not have a name)

With those 3 concepts in mind, take a look at this code

1let ages = [22, 45, 12, 6];
2
3ages.forEach((age) => {
4  console.log(age);
5});

Don't panic, we'll break this down.

ages.forEach() is a function that exists on all arrays and it takes a function as it's first input.

1(age) => {
2    console.log(age)
3})

The above is an anonymous function that we create and pass into .forEach()

You can see that this anonymous function has an input argument called age, we could have called it anything we wanted but since we are using this on an array of ages it's a good name.

So finally, what is forEach doing?

Well, it iterates over the ages array and executes whatever function it was given for each element of the array.

Here's another example in a playground

This time we have an array called words so for the function we pass in it makes sense to call the input argument word.

It doesn't really matter what we call the input argument though so long as it makes sense to us. Since our function is just printing the array element it's given we could write it in a really generic way.

1let words = ["All", "the", "code"];
2
3words.forEach((thingToLog) => {
4  console.log(thingToLog);
5});

We could even break it out as a true function that we could use in as many forEach's as well like.

forEach is a higher order function. It exists expressly to take another function and execute it for each item of an array.

You might be wondering why this is useful when we already have a number of ways of running loops, well you'll see 😀

On to the more useful ones!

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co