-2

Can anyone clearly explain how arguments are being passed to "log" function and then to "add" functions in the following code.

const add = (x,y) => console.log(x+y);

const log = func => (...args) => {
  console.log(...args);
  func(...args);
}

const logadd = log(add);
logadd(1,2,3); // 3 //1,2,3

I know the above code can also be written as follows

const add = function(x,y) {
  console.log(x,y);
}

const log = function(func){
   return function(...args){
    console.log(...args);
    func(...args)
  }       
}

const logadd=log(add);
logadd(1,2,3); // 3 //1,2,3

If logadd is function variable and if I pass it arguments how are the arguments passed to, first log function and then to add function? Any nice articles that explain this or can anyone explain this?

joatmom1
  • 13
  • 5
  • Hints: *Currying function, spread operator* – Rajesh Mar 22 '17 at 07:56
  • If you understood the bottom variant, understanding the top one is simple: `func => ___` is (mostly) equivalent to `function(func) { ___ }`, and `(...args) => ___` is (mostly) equivalent to `function(...args) { ___ }`. With those substitutions, the two code blocks are literally a copy-paste of each other. – Amadan Mar 22 '17 at 08:06
  • Hi @Amadan I understand what you explained and with that understanding only I wrote the first block is the same as second block. However what I didn't understand is how the args were passed through to inner function magically? – joatmom1 Mar 22 '17 at 09:56
  • @Rajesh thanks I will look into Currying function – joatmom1 Mar 22 '17 at 09:56
  • I am not sure why this question has been down voted? can anyone care to explain? – joatmom1 Mar 22 '17 at 09:56

1 Answers1

0

First of all arrow functions are just called arrow functions - they are neither fat nor thin.

In func => (...args) the args argument is used as a rest parameter (indicated by ...) to collect all given arguments in an Array ([1,2,3] in your example). With console.log(...args) the spread syntax ... is used to apply the console.log method to all elements of the args array. Please note that the meaning of the ... syntax varies depending on the context.

func(...args) is evaluated to func(1,2,3). Since func represents add, it discards the third argument.

log is a higher order function, i.e. a function that takes another function as its argument. This has nothing to do with currying, though currying facilitates the use of higher order functions. However, log is partially applicable in its first argument.

  • Thanks @ftor, that makes sense. The missing link in my understanding was High order functions. Do you suggest any good articles to read more about these? – joatmom1 Mar 22 '17 at 11:10
  • Of course: [function composition](http://stackoverflow.com/a/30198265/6445533) is one of the most important higher order functions. This is a good starting point. There are many more though. –  Mar 22 '17 at 11:14