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
When you run the
forEach(artist = > {/*something*/})
, you are making the callback function, which gets called for every element in the array. Theartist =>
part is passingartist
as an argument. Within the newly created function, you can use the artist parameter, which will be one of the artists from theartists
array. This is why you can also use.forEach()
like this as well: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 theconsole
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