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

Michael Bijnens
Michael Bijnens
2,095 Points

Hey guys, I'm getting the error message "number is not defined here". Can somebody tell me what I am doing wrong?

In the video about writing callback functions as arrow functions Guil also uses a new undefined argument called movie.

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

1 Answer

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 => number * 5); // number is only defined within the scope of this function, and you're not storing it anywhere
times5.push(number); // you're outside the scope of the function here

what you have can be rewritten like this, using traditional functions

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

what you could do is this

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)
});

which would be equivalent of this

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));

even better would be to use the map method, instead of forEach.

const numbers = [1,2,3,4,5,6,7,8,9,10];

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

const times5 = numbers.map(number => number*5);