ES6 Destructuring
ES6 Destructuring
Destructuring is a succinct way to access:
- Elements of an array
- Properties of an object
For example, It is perfectly fine to use the following syntax when you need to bind elements of an array to standalone variables.
let continents = ["Africa", "Asia", "Australia"]
let [continentA, continentB, continentC] = continents
console.log(continentA) //OUTPUT Africa
console.log(continentB) //OUTPUT Asia
console.log(continentC) //OUTPUT Australia
This method seems rather unnecessary because the legacy method of using indexes to access array elements already exists. However, this method is a handy tool when it comes to writing clean, concise code. Consider the function below, It takes an array as arguments and returns the sum of its elements.
function getSum([element1, element2, element3]){
return element1+element2+element3
}
let array=[1,2,3]
console.log(getSum(array)) //OUTPUT 6
A similar trick works for objects, using curly braces instead of square brackets.
let continent={name:"Africa", population:1200000000}
let {name}=continent
console log(name) //OUTPUT Africa