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

I need help.

I'm learning this and I got stuck.

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

numbers.forEach (function (times5) {
 alert(times5);
})

1 Answer

Hi Daniela!

Two issues:

1) You need to multiply each element in the numbers array by 5

2) Then you need to add the new values to the times5 empty array (use the numbers array's push method)

This passes:

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

numbers.forEach (function (number) {
    times5.push(number*5);  // both steps happen here
});

You can also use an ES6 fat arrow funtion and it still passes:

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
numbers.forEach(number => {
    times5.push(number*5);
});

More info:

https://www.freecodecamp.org/news/javascript-foreach-how-to-loop-through-an-array-in-js/

https://www.w3schools.com/jsref/jsref_foreach.asp (Here they write the callback function outside the forEach loop.)

So this also passes:

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
numbers.forEach(multiplyBy5andAddToArray);

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

I hope that helps!

Stay safe and happy coding!

Thanks for helping me.