Declaration of key variables in Javascript

Asked

Viewed 1,081 times

4

I recently saw a type of Javascript code, in some examples of Electron, which I believe is part of ES6. These are variable statements 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 is being used with const, but I don’t 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 between keys.

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

  • 1

    Sérgio already answered your question, but if you want to declare these keys to get several properties of an object it would be better to declare the with instead. Example: var obj = {prop: 5, ah: 2, uuh: true, y: false}; with(obj) { alert(prop); }. The with expands an object and is supported from ES1.

1 answer

9


This is a new technology called destructuring assignment and which in practice is a shortcut for declaring variables with the same name as an object property, 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 of

const foo = obj.foo;

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

const {foo, bar} = obj;

which is even that

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

This can also be done in arrays, in this case the array positions are imported:

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 very 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:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.