My FeedDiscussionsHashnode Enterprise
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

ES6 Destructuring

CHACHA IAN's photo
CHACHA IAN
·Dec 25, 2021·

1 min read

ES6 Destructuring

Destructuring is a succinct way to access:

  1. Elements of an array
  2. 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