ES6: Object Destructuring

Sahar E.Hassan
2 min readMar 18, 2019
ES6 new feature: destructuring

ES6 introduced a new feature that makes it easier to deal with arrays and objects which is “destructuring”.

Actually destructring is one of my favorite features that came along with ES6. Today we’re going through object destructring specifically.

Why destructuring?

Assume we have an object with more than one property and we want to read them all.

let myObj = {
name: 'Sahar',
age: 20,
gender: 'female'
}
console.log(myObj.name); //Saharconsole.log(myObj.age); //20console.log(myObj.gender); //female

As you see we’ve to write object name followed by dot ( . ) then property name in case we want to use any of those properties, it seems to be simple and silly in this example but it’ll be the opposite if we have nested objects.

What is destructuring:

Simply, destructring is breaking down complex structure into simpler parts.

How to use object destructuring:

let myObj = {
name: 'Sahar',
age: 20,
gender: 'female',
grades:{
math: 70,
english: 85,
science: 65
}
};
// read any of grades
console.log(myObj.grades.math) //70

We can write the above code in simpler way using ES6 destructuring:

let myObj = {
name: 'Sahar',
age: 20,
gender: 'female',
grades:{
math: 70,
english: 85,
science: 65
}
};
//ES6 object destructrue
const {name, age, gender, grades:{ math, english, science }}= myObj;
console.log(name); //Sahar
console.log(math); //70

Also you can give any property an alias name:

let myObj = {
name: 'Sahar',
age: 20,
gender: 'female',
grades:{
math: 70,
english: 85,
science: 65
}
};
const {name: studentName, age: studentAge} = myObj;console.log(studentName); //Sahar
console.log(studentAge); //20

Actually it’s as simple as that. hope you enjoyed reading the article, all comments and feedback are highly appreciated. Have a nice day :)

--

--