Friday, October 25, 2019

[JS][Example] JavaScript ES6 feature : Destructuring Assignment

According from the defination : "The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables."

Example 1 - array destructuring

ECMAScript 6 :
var a = ["str1","str2"];
var [b,c] = a;
If you print variable b, you would get result as str1

script write by ECMAScript 2015:
var a = ["str1", "str2"];
var b = a[0],
    c = a[1];

========================================

Example 2

ECMAScript 6 :
let o = {name: "Sam", age: 45, gender:"M"};
let {name, age, gender} = o;
document.write(name);
document.write(age);
document.write(gender);
Result is Sam45M

script write by ECMAScript 2015:
var o = {
  name: "Sam",
  age: 45,
  gender: "M"
};
var name = o.name,
    age = o.age,
    gender = o.gender;
document.write(name);
document.write(age);
document.write(gender);
========================================

Example 3

ECMAScript 6 :
let people = [{name:"Sam",age:45,gender:"male"},
              {name:"Ann",age:15,gender:"female"}]
for(let i in people){
 let {name,age,gender} = people[i];
   document.write(`${name} is ${age} years old and is ${gender}. `);
}
Result is Sam is 45 years old and is male. Ann is 15 years old and is female.

script write by ECMAScript 2015:
var people = [{
  name: "Sam",
  age: 45,
  gender: "male"
}, {
  name: "Ann",
  age: 15,
  gender: "female"
}];
for (var i in people) {
  var _people$i = people[i],
      name = _people$i.name,
      age = _people$i.age,
      gender = _people$i.gender;
  document.write("".concat(name, " is ").concat(age, " years old and is ").concat(gender, ". "));
}

Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

No comments :

Post a Comment