Javascript function parameter with object designator

What's the difference between

function updateSomething(item) {}

and

function updateSomething({items}) {}

? the item variable in the first one can also be an object, why does the second use object notation? When should you use the first and last?

+4
source share
2 answers

This is a restructuring of parameters starting with ES2015. In the second case, you initialize the local variable with the value of the itemsargument property .

function updateSomething({items}) {

roughly equivalent

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

Some other examples here and here .

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

, Edge Safari (. ), , Babel.

+4

ES6 item , , :

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

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

ES5 :

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

2ality , , .

, destructure item.

, :

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
}

, :

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

All Articles