What use are the keys in the variables of Node.js

Asked

Viewed 271 times

1

ola, I have a doubt a little amateur I’m starting with Node.js and through my learning I came across a situation and I would like to understand, in one of the codes I researched I found a variable declared the name between keys as the example below

const { home } = app.controllers;

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

1 answer

3


The name for the expression given as an example is "Assignment via structuring (destructuring assignment)".

Assignment via structuring (destructuring assignment).

The syntax of assignment via structuring (destructuring assignment) is a Javascript expression that allows you to extract data from arrays or objects in different 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 property home of the variable app.controllers directly to a constant of the same name. Other ways of performing the same assignment would be:

const home = app.controllers.home;

// Ou

const { controller: { home } } = app;

Browser other questions tagged

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