What is the difference between object destructuring and normal object assignment in Javascript ES6?

What is the difference between these two code examples (apart from the syntax, of course)?

EXAMPLE 1:

var user = {
   name: 'Diego',
   age: 25
}

var {name} = user;

console.log(name); // Diego

EXAMPLE 2:

var user = {
   name: 'Diego',
   age: 25
}

var name = user.name;

console.log(name); // Diego

Both examples assign the same value. I do not understand what is the difference or advantage / advantage of use.

+4
source share
2 answers

Let me extend this to several properties:

var {foo, bar, baz} = user;

In traditional syntax, this would be:

var foo = user.foo,
    bar = user.bar,
    baz = user.baz;

So, for each property, we must repeat the object we want to access ( user), and the name of the property foo = ... .foo. New syntax makes it easy to repeat yourself.

, :

var {foo, bar, baz} = getUser();

var foo = getUser().foo,
    bar = getUser().bar,
    baz = getUser().baz;

getUser (- ) ( ). , , .

+9

, :

var user = {
   name: 'Diego',
   age: 25
}

var {name, age} = user;

name, age .

+3

Source: https://habr.com/ru/post/1670171/


All Articles