Destructuring in ES6
The destructuring syntax makes it easier to assign values to a new variable.
- Array Destructuring – show you how to assign elements of an array to variables.
function getScores() {
return [70, 80, 90];
}
Before ES6
var x = scores[0],
y = scores[1],
z = scores[2];
console.log(scores[0]);
console.log(scores[1]);
console.log(scores[2]);
Now
var [x, y, z] = getScores();
console.log(x);
console.log(y);
console.log(z);
- Object Destructuring – learn how to assign properties of an object to variables.
constperson = {
name
:
'Shairy',
age
:
32,
gender
:
'male'
}
Before ES6
letname = person.name;
let age = person.age;
let gender = person.gender;
console.log(name);
console.log(age);
console.log(gender);
Now
let { name, age, gender } = person;
console.log(name);
console.log(age);
console.log(gender);
really helpful guide