What is the key for the variables in node.js

0

Hello, I have a little amateur doubt I'm starting with node.js and through my learning I came across a situation and would like to understand, in one of the codes that I researched I found a variable declared the name in braces as the example below

const { home } = app.controllers;

I already know how this function works but I would like to understand what the keys are for {} because when I throw them the code presents error what is the difference between const { home } = app.controllers; and const home = app.controllers;

    
asked by anonymous 02.11.2018 / 21:59

1 answer

1

The designation for the expression given as an example is " Destructuring assignment ".

  

Assignment via destructuring assignment .

     

The destructuring assignment syntax is a JavaScript expression that enables you to extract data from arrays or objects into distinct variables.

var a, b, rest;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

[a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]

({a, b} = {a:1, b:2});
console.log(a); // 1
console.log(b); // 2

In your example you are assigning the home property of the app.controllers variable directly to a constant of the same name. Other ways to accomplish the same assignment would be:

const home = app.controllers.home;

// Ou

const { controller: { home } } = app;
    
05.11.2018 / 12:14