Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arrow functions: destructuring arguments and grabbing them as a whole at the same time

Can we do both destructuring: ({a, b}) => ( a + b ) and grab the arguments: (...args) => ( f({...args}) ), at the same time for arrow functions in ES6.

Looking for something like (...args = {a, b}) => ( a + b + f({...args}) ).

My curent solution is to do something like:

({a, b}) => {
  const {...args} = {a, b}
  return a + b + f({...args})
}

But it is redundant or (thanks to nnnnnn & Dmitry)

(args) => {
  const {a, b} = args
  return a + b + f({...args})
}

which is less redundant and definitely better but still not entirely satisfactory.

like image 242
Adrian Silvescu Avatar asked Nov 05 '17 01:11

Adrian Silvescu


People also ask

Can arrow functions have arguments?

There are differences between arrow functions and traditional functions, as well as some limitations: Arrow functions don't have their own bindings to this , arguments or super , and should not be used as methods.

Where should you not use arrow functions?

An Arrow function should not be used as methods. An arrow function can not be used as constructors. An arrow function can not use yield within its body. Arrow function cannot be suitable for call apply and bind methods.

Do arrow functions expose the arguments object?

Arrow functions don't have their own arguments object. Arrow functions do not expose an arguments object to their code: arguments.

What is the difference between Destructuring an object and Destructuring an array?

The main difference between the two destructuring assignments is this: Array destructuring extracts values from an array. But object destructuring extracts values from a JavaScript object.


1 Answers

You can use default parameters and object rest at target of destructuring assignment for first parameter, where a single object is expected, and optionally define subsequent parameters by destructuring previously defined object parameter

const fn = ({...args} = {}, {a, b} = args) => console.log(a, b, args);
like image 64
guest271314 Avatar answered Sep 25 '22 13:09

guest271314