Declaration of variables with keys in Javascript

3

Recently I've seen a JavaScript code type, in some examples of Electron, which I believe to be part of ES6. They are variable declarations in the following format:

const electron = require('electron');
// Module to control application life.
const {app} = electron;
// Module to create native browser window.
const {BrowserWindow} = electron;

Here it is being used with const , but I do not know if this also exists with let and var .

The important thing here is that instead of declaring in the usual way

const app = electron;
const BrowserWindow = electron;

We're putting app and BrowserWindow in braces.

What does this kind of declaration mean with the name of the variable inside braces? When and how should this type of declaration be used?

    
asked by anonymous 29.06.2016 / 19:22

1 answer

7

This is a new technology called destructuring assignment and that in practice is a shortcut to declaring variables with the same name as a property of an object, or in arrays declare indexing to the position of an array.

For example:

var obj = {
  foo: 20,
  bar: 50
};

const {foo} = obj;

console.log(foo);

is a shortcut from

const foo = obj.foo;

This is practical and can be used in more than one at a time:

const {foo, bar} = obj;

What is it that is

const foo = obj.foo;
const bar = obj.bar;

This can also be done in arrays, in this case you import the positions of the array:

var arr = [0, 5, 10];
const [primeiro, segundo] = arr;

console.log(primeiro, segundo); // 0, 5

which is the same as:

var primeiro = arr[0];
var segundo = arr[1];

Another useful way is in function arguments:

var Ana = {
    nome: 'Ana',
    idade: 34
}

function info({nome,idade}) {
    console.log('Pessoa: ${nome}, Idade: ${idade}');
}

info(Ana); // Pessoa: Ana, Idade: 34

Notes:

  • Example: link
  • This technology can be used in const , var , let , import or function arguments.
29.06.2016 / 19:27