The simplest example to put it better is with an arrow functionsuma
const suma = ({a, b}, c) => a + b + c;
console.log(suma({ a:10, b:17}, 100)); // 127
or How does a separate argument work?
The simplest example to put it better is with an arrow functionsuma
const suma = ({a, b}, c) => a + b + c;
console.log(suma({ a:10, b:17}, 100)); // 127
or How does a separate argument work?
It is important to mention that there is no separate argument, 2 arguments are being passed to the function:
{ a, b }
)c
)And then allocation by destructuring is being done . This is a JavaScript expression (also present in other languages such as Python or Perl) that allows the extraction of data using a syntax that is equivalent to the construction of arrays and objects.
In this case, you are telling the function that the first parameter is going to be an object that is going to have the properties
a
andb
, and to unstructure it to use the variablesa
andb
equivalent to those propertiesa
andb
of the object.But an example is worth a thousand words. The code you have right now for
suma
:would be (more or less) equivalent to doing the following without arrow notation and without destructuring:
You can see both methods compared here:
As a note, it is important to indicate that the names of the properties used must exist in the object or errors will occur. For example, this code will fail because the object has no property
b
(onlya
andd
):And that also works "in reverse": you can pass an object with more properties and then only use a few of them. In the following example you can see how an object is passed
suma
that has the propertiesa
,b
andd
, but we are only going to usea
andb
which are the ones indicated in the parameter of the arrow function:It depends on how you require the method to receive the data, in the case you show, the second argument is a value that is not received as an object in the function,
The function obtains the 2 values of the object (
{a, b}
) which it adds together (a + b
) and these in turn add them to the second value that the function receives (c
):You can not use a second argument and add the value of the second argument to
objeto
, in this case the values of are obtainedobjeto
and added, your function would receive only one argument: