skip to Main Content

In the below example from Codecademy, I don’t really understand how the console can process the ‘artist’ parameter in a higher-order function, considering that we’ve only declared ‘artists’ up to this point?

const artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];

artists.forEach(artist => {
  console.log(artist + ' is one of my favorite artists.');
});

How can we use ‘artist’ and not something like:

artist[i]

2

Answers


  1. When you run the forEach(artist = > {/*something*/}), you are making the callback function, which gets called for every element in the array. The artist => part is passing artist as an argument. Within the newly created function, you can use the artist parameter, which will be one of the artists from the artists array. This is why you can also use .forEach() like this as well:

    const artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];
    function printArtist(artist) {
           console.log(artist + ' is one of my favorite artists.');
    }
    artists.forEach(artist => printArtist(artist))
    
    Login or Signup to reply.
  2. considering that we’ve only declared artists up to this point?

    No, in the callback function scope artist is also declared: you’ve defined it as the first parameter of the arrow function.

    Notice that this is neither specific to forEach nor to the console call, it’s just an ordinary function parameter and used as such in the code. artist is just a variable that has the value that was passed to the function. Same as

    const artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];
    const action = (artist) => {
      console.log(artist + ' is one of my favorite artists.');
    };
    artists.forEach(action);
    // or
    for (const arrEl of artists) action(arrEl);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search