6

What is the differences between

function updateSomething(item) {}

and

function updateSomething({items}) {}

? item variable in the first one can be an object too, why does the second one use an object notation? When should I use the first one and the latter one?

3
  • I don't think this is valid - function updateSomething({items}) {} Commented May 24, 2016 at 15:23
  • @Mike It is, now (for the right engine or some transpiler) Commented May 24, 2016 at 15:29
  • Thanks @DenysSéguret . Didn't know, will read about it. Commented May 24, 2016 at 15:34

2 Answers 2

5

This is parameter destructuring, from ES2015. In the second case, you're initializing a local variable to the value of the items property of the argument.

function updateSomething({items}) {

is roughly equivalent to

function updateSomething(obj) {
     var items = obj.items;

Some other examples here and here.

And from the MDN: Pulling fields from objects passed as function parameter

Note that this syntax isn't yet available in Edge or Safari (see compatibility map) so you might want to use a transpiler like Babel.

Sign up to request clarification or add additional context in comments.

Comments

2

The second example is using the shorthand for ES6's parameter destructuring to extract the item property from the first parameter, assuming it is an object:

function destructure({item}) {
  console.log(item);
}

destructure({item: 3}); // logs "3"

The ES5 equivalent would be:

function destructure(arg1) {
  var item = arg1.item; // or throw
  ...
}

This blog post by 2ality has an excellent writeup of destructuring, parameters, and how they play together.

This will throw an error if the first argument to destructure does not have an item property.

You can specify the parameter to destructure or combine this with defaults using:

function ({foo, bar} = param) {
  console.log(foo, bar); // the rest of param is not available
}

function ({foo, bar = 11} = param) {
  console.log(foo, bar); // bar will be 11 if it was not set in param
}

There are a number of variations on this syntax, but it's the counterpart to the object shorthand syntax:

const item = 3;
destructure({item}); // creates an object like {item: item}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.