javascript - High order functions explanation when passing a function to another function -
javascript - High order functions explanation when passing a function to another function -
i need help breaking downwards line line happens in illustration (an excerpt eloquent javascript):
we have foreach function logs every item in array. understand how works.
function foreach(array, action) { (var = 0; < array.length; i++) action(array[i]); }
so have array called 'numbers' , variable called 'sum' set 0. lost when 'function(number)' gets passed the action parameter. , how work? don't see it's value is. can break down?
var numbers = [1, 2, 3, 4, 5], sum = 0; foreach(numbers, function(number) { sum += number; }); console.log(sum); // → 15
i think you're not grasping syntactic construction of call. 1 as write
var numbers = [1, 2, 3, 4, 5]; var sum = 0; function addtosum(number) { sum += number; } foreach(numbers, addtosum);
i hope clear happening in here. have function addtosum
, , pass function foreach
function - refer parameter name action
, , phone call each element of passed array in body of loop: action(array[i])
. great deal abstraction can pass arbitrary function foreach
…
so odd syntax now? first, replacing function declaration function expression. function look expression evaluates function object, array literal [1, 2, 3, 4, 5]
evaluates array object. it's called anonymous function not have name. take value , assign variable:
var numbers = [1, 2, 3, 4, 5]; var sum = 0; var addtosum = function(number) { sum += number; } foreach(numbers, addtosum);
nothing has changed until here. now, why need variable? don't need identifiers pointing values created expressions. set expressions straight in foreach
function phone call - still passing same values (foreach
not spot difference):
var sum = 0; foreach([1, 2, 3, 4, 5], function(number) { sum += number; });
javascript function
Comments
Post a Comment