Sean
Sean

Reputation: 981

javascript function parameter with object notation

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?

Upvotes: 6

Views: 1638

Answers (2)

ssube
ssube

Reputation: 48287

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}

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382264

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.

Upvotes: 5

Related Questions