1

The app at my work (React.js) requires me to pass functions around a lot, and often I have to do this: (es6 javascript)

({ ...args }) => this.props.exampleFunc({ newArg, ...args })

Taking a func I had and doing this to inject an argument without calling it. I was reading about closures and I thought that might be what this, but I wasn't sure I fully understood. Is that what this is?

Edit: to clarify, I'm not talking about the arrow, I'm just talking about the trick with the newArg

thefistopher
  • 429
  • 1
  • 5
  • 15
  • Yes, the arrow function closes over `this`, making it a closure. – Bergi Jul 11 '18 at 15:42
  • Possible duplicate of [What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?](https://stackoverflow.com/questions/24900875/whats-the-meaning-of-an-arrow-formed-from-equals-greater-than-in-javas) – Igor Jul 11 '18 at 15:46
  • @Igor I'm not talking about the arrow, sorry for the confusion – thefistopher Jul 11 '18 at 15:47
  • I am not following, what trick with `newArg`? It is an assigned value on a new object that is being passed into the `exampleFunc`, it probably exists outside the function I am thinking but without more code I could not say. – Igor Jul 11 '18 at 15:49
  • That's what I'm referring to. Just wondering if there was a name for doing that. – thefistopher Jul 11 '18 at 15:51
  • IE. if a function took in three arguments, and you did this so that it only required two arguments – thefistopher Jul 11 '18 at 15:52
  • `{ newArg, ...args }` is shorthand for creating a clone of the original object argument and adding an additional property to it. – Barmar Jul 11 '18 at 16:25
  • Your code is equivalent to `(argObj) => this.props.exampleFunc(Object.assign({ newArg }, objArg))` – Barmar Jul 11 '18 at 16:27

1 Answers1

0

It's an arrow function, and yeah, it's a sort of a closure (if it uses names from the outer scope).

Compared to regular ol' function() {} functions, arrow functions also capture this from the outer scope, which is useful in all sorts of object-oriented situations.

AKX
  • 152,115
  • 15
  • 115
  • 172