Javascript

having trouble with .forEach functions, please help
I do not fully understand how to use the .forEach functions

First of all let me refer you to the official documentation:

But to give a summary.

forEach is a method takes each single array item and does with it whatever you tell it to do. In order to do so you need to chain it to the array.

What it is you want to do is what you write between the brackets in the form of a callback function that takes at least one input parameter. forEach then passes each array item as an argument to this callback function. The name of this input parameter can be anything you like. The forEach method will always pass each array item to it.

For example:

// Example
let array = [1, 2, 3, 4, 5];
array.forEach(function(number) {
   console.log(number)
});

// result, the following numbers are printed in the console:
1
2
3
4
5

The callback function takes each number from the array as an argument for its input parameter. It then logs each number to the console.

To add to the confusion, the above mentioned function can be written shorter using a shorthand arrow notation, like so:

array.forEach(number => console.log(number));

Hope this helps.

Happy coding!

forEach element in some array, do this thing to it (that’s the function part).

const shoes = [“Nikes”, “Adidas”, “Vans”, “Soul Boots”];

shoes.forEach(function(shoeName) {
    console.log(`I really need to buy a pair of ${shoeName}.`);
});

The output:
I really need to buy a pair of Nikes.
I really need to buy a pair of Adidas.
I really need to buy a pair of Vans.
I really need to buy a pair of Soul Boots.