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?
We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property names.
Using an Object Literal This is the easiest way to create a JavaScript Object. Using an object literal, you both define and create an object in one statement. An object literal is a list of name:value pairs (like age:50) inside curly braces {}.
A JavaScript function can have any number of parameters. The 3 functions above were called with the same number of arguments as the number of parameters. But you can call a function with fewer arguments than the number of parameters.
You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj. sum(2, 2) . An object's property can point to a function, just like it can point to a string, number or other values.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With