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
Simon Tanner
5,776 PointsUnderstanding parameters and arguments
Hi, please could you help me with understanding the following code from 'eloquent javascript'. I am stuck on how the number parameter in the var myFunction = function(number) receives a number from the array in var numbers. I understand that the 'number' parameter acts as a variable but can't work out how it is given the 1,2,3,4,5 from the array. Hope this makes sense as a question?!
function forEach(array, action) { //1st parameter is an array, the 2nd is a function
for (var i = 0; i < array.length; i++)
action(array[i]); //The function is used, with each element of the array as parameter
}
var numbers = [1, 2, 3, 4, 5], sum = 0;
var myFunction= function (number) { //I declare a function which receives a number
sum += number; //and adds it to sum.
}
forEach(numbers,myFunction); //I call the forEach function using the
// variables I previously created as parameters
console.log(sum);
2 Answers
Stan Goldmann
2,035 PointsYou declare a function called forEach and pass an array to it.
It counts how many indexes are in that array and declares current for-loop run as 0.
(Since numeric arrays with no specified index will always start from 0)
In that loop you're calling your second parameter, action, which is your function myFunction.
This function takes a number to add this to sum.
Your array has 5 values, so it hat an index from 0-4.
Your for loop will start from 0 until it hits the last index, which is 4.
For each index it'll take its value and pass that into myFunction.
So the first loop will look like this :
- action(array[0]) same as -> myFunction(1)
- action(array[1]) same as -> myFunction(2)
- action(array[2]) same as -> myFunction(3)
...and so on.
So it loops through all indexes of that array and calls the function on that VALUE of the INDEX.
Simon Tanner
5,776 PointsSorry about the formatting...
Simon Tanner
5,776 PointsSimon Tanner
5,776 PointsThanks a lot Stan, that's a really clear and helpful explanation. I think I've nearly grasped what's going on!