Object Destructuring in ES6 Similar to Array destructuring, Object destructuring unpacks properties into distinct variables. For example: let obj = {h:100, s: true}; let {h, s} = obj; console.log(h); // 100 console.log(s); // true Try It Yourself We can assign without declaration, but there are some syntax requirements for that: let a, b; ({a, b} = {a: 'Hello ', b: 'Jack'}); console.log(a + b); // Hello Jack Try It Yourself The () with a semicolon (;) at the end are mandatory when destructuring without a declaration. However, you can also do it as follows where the () are not required: let {a, b} = {a: 'Hello ', b: 'Jack'}; console.log(a + b); Try It Yourself You can also assign the object to new variable names. For example : var o = {h: 42, s: true}; var {h: foo, s: bar} = o; //console.log(h); // Error console.log(foo); // 42 Try It Yourself Finally you can assign default ...
Comments
Post a Comment