What does function ({Something, something More, still More}) {} mean? in Javascript

5

Watching a tutorial I found an expression like this:

 function ( { algo, algoMas, todaviaMas } ) {

    }  

Doing a bit of research, I found Destructuring in ES6 : The unstructured data, or

  

destructuring named parameter:

"destructure the named parameters" ; but I can not understand how it works and how to apply it.

Thank you in advance for the help.

    
asked by julio 22.08.2018 в 23:56
source

2 answers

1

Suppose we have this function:

function f({algo, algoMas, todaviaMas}) {
    //...
}

This would be equivalent to writing something like this:

function f(o) {
    var algo = o.algo;
    var algoMas = o.algoMas;
    var todaviaMas = o.todaviaMas;
    //...
}

As you will see it is a way to use a more compact syntax for the assignment of variables that are part of an object that is received as a parameter in this case.

Example, the following two snippets do the same:

Without destructuring

function f(o) {
    var algo = o.algo;
    var algoMas = o.algoMas;
    var todaviaMas = o.todaviaMas;
    
    console.log('algo: ${algo}');
    console.log('algoMas: ${algoMas}');
    console.log('todaviaMas: ${todaviaMas}');
}

var o = {
  algo: 1,
  todaviaMas: 2,
  algoMas: 3
};

f(o);

With destructuring

function f({algo, algoMas, todaviaMas}) {
    console.log('algo: ${algo}');
    console.log('algoMas: ${algoMas}');
    console.log('todaviaMas: ${todaviaMas}');
}

var o = {
  algo: 1,
  todaviaMas: 2,
  algoMas: 3
};

f(o);
    
answered by 23.08.2018 / 07:27
source
0

The subject really is not difficult, but to understand the Destructuring assignment you have to study it from the simplest and explain it to the most functional and useful that this new javascript syntax brings.

This would really take many lines of code since, to learn it, you have to see how it works with examples. so better I leave a link where you find the whole explanation from the simplest and with many examples. (in English) .

Destructuring Assignment

    
answered by 23.08.2018 в 06:32