What is the use of having a separate argument in a function in JavaScript?

Question:

The simplest example to put it better is with a suma arrow function

const suma = ({a, b}, c) =>  a + b + c;
    
    console.log(suma({ a:10, b:17}, 100)); // 127

o How does a separate argument work?

Answer:

It is important to mention that there is no separate argument, 2 arguments are being passed to the function:

  • The first will be an object (specified by { a, b } )
  • The second will be a variable (to be called c )

And so it is doing allocation by destructuring . This is a JavaScript expression (also present in other languages ​​such as Python or Perl) that allows data extraction 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 and b , and that it deconstructs it to use the variables a and b equivalent to those properties a and b of the object. .

But an example is worth a thousand words. The code you have right now for suma :

const suma = ({a, b}, c) =>  a + b + c;

would amount (more or less) to doing the following without arrow notation and without destructuring:

const suma = function(obj, c) {
  var a = obj.a;
  var b = obj.b;
  var c = c;
  return a + b + c;
}

You can see both methods compared here:

const suma = ({a, b}, c) =>  a + b + c;   
console.log(suma({ a:10, b:17}, 100)); // 127

const suma2 = function(obj, c) {
  var a = obj.a;
  var b = obj.b;
  var c = c;
  return a + b + c;
}
console.log(suma2({ a:10, b:17}, 100)); // 127

As a note, it is important to note 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 does not have property b (only a and d ):

 const suma = ({a, b}, c) => a + b + c; console.log(suma({ a:10, d:17}, 100)); // NaN porque b no existe

And that also works "the other way around": 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 to suma that has the properties a , b and d , but we are only going to use a and b which are the ones indicated in the parameter of the arrow function:

const suma = ({a, b}, c) =>  a + b + c;   
console.log(suma({ a:10, b:17, d:10}, 100)); // 127 (d se ignora)
Scroll to Top