0

Can somebody explain to me, in detail, how the spread operator works when used to get the parameters of an input function (function passed in as a parameter to another function)?

For example, consider a simple throttle function:

const throttle = (func, wait) => {
  let halt = false
  return function(...args) {
    if (!halt) {
        func.call(this, ...args)
        halt= true
        setTimeout(()=>halt=false, wait)
    }
  }
}

In the above sample, ...args is used twice, once as the parameter of the inner arrow function, and the other time is passed as parameters to the func call.

I am having a hard time understanding what ...args is exactly. I know that if you use ... on an array of items, it will simply deconstruct the array and spread them out to individual items. But what exactly is being spread here when the expected parameters are a function(probably with its own parameters) and a number? Also, when using the apply on func, why are we spreading again?

Isaac
  • 49
  • 1
  • 7
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – evolutionxbox Jun 09 '21 at 11:17
  • Does this answer your question? [Spread Syntax vs Rest Parameter in ES2015 / ES6](https://stackoverflow.com/questions/33898512/spread-syntax-vs-rest-parameter-in-es2015-es6) – evolutionxbox Jun 09 '21 at 11:18
  • Btw, the `this` keyword doesn't work as one would expect to when you use an arrow function here. Use a normal `function` instead for the returned closure. – Bergi Jun 09 '21 at 11:22
  • @Bergi Oh yes you are correct since the arrow function has a lexical ```this```. And I guess I am still a little confused, so maybe clarify this for me: the first ```...args``` is the spread operator, and the second ```...args``` is the rest operator correct? How is this getting me the parameters passed into the ```func`` function? – Isaac Jun 09 '21 at 11:58
  • @Isaac The other way round. And [neither is an operator](https://stackoverflow.com/q/44934828/1048572). In a parameter list, it's the rest parameter syntax, in a function call, it's spread syntax. – Bergi Jun 09 '21 at 12:14
  • "*when using the apply on func, why are we spreading again?*" - you're not using `apply`, your using `call`. But you're right, if the code was using `apply`, it would be just `func.apply(this, args)`, no spread syntax. – Bergi Jun 09 '21 at 12:16
  • @Bergi Ah thank you! That makes a lot more sense now :) – Isaac Jun 09 '21 at 12:20

0 Answers0