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

后端 未结 2 1288
孤街浪徒
孤街浪徒 2021-01-12 21:38

What\'s the difference between this two code examples (besides the syntax of course)?

EXAMPLE 1:

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

var         


        
相关标签:
2条回答
  • 2021-01-12 22:02

    Let's extend this to multiple properties:

    var {foo, bar, baz} = user;
    

    In the traditional syntax, this would be:

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

    So for every property, we have to repeat the object we want to access (user) and the name of the property foo = ... .foo. The new syntax makes it easier to repeat yourself less.

    There's another difference if the object isn't already stored in a variable:

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

    Now we can't just do

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

    because each call to getUser might do different things (due to side effects) or just be inefficient (because we're repeating work). We'd have to create a new local variable to store the object in, just to initialize the three variables we actually care about.

    0 讨论(0)
  • 2021-01-12 22:06

    There's no effective difference, but destructuring is convenient:

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

    That declares and initializes both name and age in one statement without redundant mentions of the property names.

    0 讨论(0)
提交回复
热议问题