I am learning JavaScript from an eloquent book and in the chapter about higher order functions I found this code:
function noisy(f) { return function(...args) => { console.log("calling with", args); let result = f(...args); console.log("called with", args, "returned", result); return result; }; } noisy(Math.min)(3,2,1); // calling with [3,2,1] // called with [3,2,1] returned 1
I know that the rest parameter ...args
takes a number of arguments and groups them into an array, but when did I gave any parameter to the arrow function?
Does args
automatically contain all the extra parameters passed to noisy()
(which is expecting only f
)?
If yes what are the rules of this way of using parameters?
Could I have used even only the first two extra parameters?
Shouldn’t the original code be like the following?
function noisy(f, ...args) { return function(args) => { // with the rest of the program
Advertisement
Answer
when did I gave any parameter to the arrow function
You passed them in the (3,2,1)
part of noisy(Math.min)(3,2,1)
. noisy()
is returning a function which you are then calling immediately with parameters (3,2,1)
it might be clearer to break out that call
var myArrowFunction = noisy(Math.min) myArrowFunction(3,2,1)