Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Quickstart Arrays and Loops Create a forEach Loop

Elaine Cadman
Elaine Cadman
2,335 Points

I can do this without the .forEach, but I am lost with the .forEach

for(var i=0; i<numbers.length; i++) { times5[i] = numbers[i] * 5; }

app.js
const numbers = [1,2,3,4,5,6,7,8,9,10];
let times5 = [];

// times5 should be: [5,10,15,20,25,30,35,40,45,50]
// Write your code below

for(var i=0; i<numbers.length; i++) {
    times5[i] = numbers[i] * 5;
}

3 Answers

Hi Elaine,

You could try something like:

numbers.forEach(function(number){
    times5.push(number * 5);
}); 

forEach is an array method, so it needs to be attached to an array

numbers.forEach()

To access each number we use the function parameter. We can call this whatever we want, in this case I chose number as its the singular version of 'numbers'.

numbers.forEach(function(number)) { }

Then we multiple the number by 5 and push it to the times5 array

times5.push(number * 5);

See MDN - forEach

Hope this helps :)

Elaine Cadman
Elaine Cadman
2,335 Points

omg thank you, this makes so much sense. Javascript syntax is hard to adjust to! I know what I want to do, but doing it is proving tricky!

Elaine Cadman
Elaine Cadman
2,335 Points

but how does it know "number" instead of "numbers"?

If you look at the link I posted under 'syntax'

arr.forEach(function callback(currentValue[, index[, array]]) {
    //your iterator
}[, thisArg]);

You can see that the first argument to the function is the current value of the array.

Each time around the loop currentValue will change. The first time around the loop, currentValue is equal to the first item in the array. Second time around the loop, currentValue is equal to the second item in the array...

We can name the current value whatever we want, writing:

numbers.forEach(function(n){
    times5.push(n * 5);
}); 

or

numbers.forEach(function(iCanPutAnythingIwantInHere){
    times5.push(iCanPutAnythingIwantInHere* 5);
}); 

Is just as valid. However, you want to call it something that is meaningful and descriptive.

Hope this helps :)

Gabriel Plackey
Gabriel Plackey
11,064 Points

For each is kinda like shorthand for a for loop. So you can the same thing while writing less code.

Elaine Cadman
Elaine Cadman
2,335 Points

YES James Anwyl very helpful, I am truly grateful for your help!

No problem :)