15

With ES6 you can destructure objects in function arguments:

({name, value}) => { console.log(name, value) }

The equivalent ES5 would be:

function(params) { console.log(params.name, params.value) }

But what if I would like a reference both to the params object and the nested properties value and name? This is the closest I got, but the drawback is that it won't work with arrow functions because they do not have access to the arguments object:

function({name, value}) {
  const params = arguments[0]
  console.log(params, name, value)
}
4
  • 2
    function(params){const {name,value}=params;console.log(params,name,value)}?
    – user2033671
    Commented Mar 2, 2018 at 18:17
  • @ProfessorAllman Yeah that comes very close. There's still an assignment line so I guess my question was: is it possible to do that in the function signature, like function({name,value}=params)
    – webketje
    Commented Mar 2, 2018 at 18:19
  • no, it only makes the core hard to read and confusing specially when you start using arrow functions. no real benefit to it. Commented Mar 2, 2018 at 18:33
  • @DayanMorenoLeon I agree, was just curious
    – webketje
    Commented Mar 2, 2018 at 18:34

2 Answers 2

7

arguments isn't available in arrow functions, and this affects how function parameters should be consistently treated in ES6.

If original parameter is used, it should be destructured inside function:

(param) => {
  const {name, value} = param;
  // ...
}

If several arguments are expected and some argument negotiation takes place (for example, similarly to arguments.length), rest parameter should be used:

(...args) => {
  const [param] = args;
  // ...
}

Boilerplate variable destructuring has its benefits; it's easier this way to debug param or args at breakpoint even if they aren't currently in use.

2
  • Thanks, I think the answer gives a good summary of idiomatic use vs available options
    – webketje
    Commented Mar 2, 2018 at 19:56
  • Sure, you're welcome. I'm using this style myself as a rule of thumb, because param destructuring looks neat, but debugging was an issue for me numerous times in arrow callbacks. Commented Mar 2, 2018 at 19:59
1

What about next:

function({name, value}, params=arguments[0]) {
    console.log(params, name, value)
}

Or:

function(params, {name, value} = params) {
    console.log(params, name, value)
}
3
  • 1
    This doesn't work using arrow functions.
    – Ele
    Commented Mar 2, 2018 at 18:46
  • @Ele updated, must work now Commented Mar 2, 2018 at 18:51
  • 1
    I find this very confusing because it seems like the function expects 2 arguments. Furthermore it will work for a single parameter, but fails when you do x({name: 'name', value: 'value'}, {name: 'name2', value: 'value2'})
    – webketje
    Commented Mar 2, 2018 at 19:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.