I’m learning javascript. I know we can pass a function to other functions after the function is defined. But I need help on understanding this example:
function map(func, array) {
var result = [];
forEach(array, function (element) {
result.push(func(element));
});
return result;
}
From what I can understand, func is an argument of map. I need to provide a function as func. But in the tutorial I’m reading, it doesn’t mention where this func come from, seems no need to specify this argument? Another example in the tutorial is the same:
function count(test, array) {
return reduce(function(total, element) {
return total + (test(element) ? 1 : 0);
}, 0, array);
}
This test function is equal to element === 0 ? 1 : 0 , but the tutorial doesn’t say I need to write down the test function. Do I need to write this test function?
EDIT: In the link to the tutorial you posted, the function passed is a pre-defined function
Math.round. My example below shows creating your own function to pass.The
mapexample shows the implementation. You’d provide the function (and the Array) when you callmap.From the looks of it, the
mappass the current item in the Array to your function, and your function should do something with it and return the result. The results your function returns are added to the new Array.we created an Array (
arr),we created a function (
my_func), which takes whatever it’s given, and multiplies it by 2.we passed both to
mapthe
mapfunction iterates ourarr, passing the current item in each iteration to our function.our function takes the current item, and returns the result of multiplying it by 2.
the
mapfunction takes that result, and adds it to the new Array.when the iteration is done, the
mapfunction returns the new Array.