Javascript ES6 Array and Object Destructuring
Tags: javascript, webdev, codenewbie, beginners
Published: 2020-01-19 17:35:51

## Array and Object Destructuring

There are two most used data structures in javascript; array and object. Array and object destructuring is a significant feature in javascript ES6.

### Array Destructuring

Usually, to access an item in an array, you would have to access the items via their indexes as shown below.
```js
const animals = ['🐑', '🐈', '🐄', '🐪', '🐖'];

console.log(animals[2])
// 🐄
console.log(animals[4])
// 🐖
```
However, you might want to assign the values of an array to separate variables. Destructuring is a clean and simple way of achieving that. With destructuring, there is no need to use indexes or loops.

Now, using destructuring in the example above, we can assign the values of the array to variables as shown in the example below: 
```js
const animals = ['🐑', '🐈', '🐄', '🐪', '🐖'];
const [sheep, cat, cow, camel, pig] = animals;

console.log(sheep)
// 🐑
console.log(cat)
// 🐈
console.log(cow)
// 🐄
console.log(camel)
// 🐪
console.log(pig)
// 🐖
```
In the same way, you can assign default values to the variables.Thus, if you have more variables than there are in the array, your variables will still have values defined.
```js
const fruits = ['🍒','🍇','🍎','🍐'];
const [
   cherries = 'Two Cherries',
   grapes = 'A lot of Grapes',
   apple = 'Red Apple',
   pear = 'One Pear',
   peach = '🍑',
   mango = '🥭'
] = fruits;

console.log(grapes)
// 🍇
console.log(pear)
// 🍐
console.log(peach)
// 🍑
console.log(mango)
// 🥭
```
We can assign value to a declared variable using destructuring.
```js
let pie, cupcake;

[pie, cupcake] = ['🥧', '🧁']
console.log(pie)
// 🥧
console.log(cupcake)
// 🧁
```
#### Variable Swap
Again, we can swap two variables in a single destructuring expression.
```js
let owl = '🦢';
let swan = '🦉';

[owl, swan] = [swan, owl]

console.log(owl)
// 🦉
console.log(swan)
// 🦢
```
### Using rest
However, trailing items in an array can be captured with a "rest" pattern
```js
let [peacock, parrot, ...restBirds] = ["🦚", "🦜", "🦢", "🦩", "🐦", "🐧", "🦅", "🦆", "🦉"];
console.log(peacock)
// 🦚
console.log(parrot)
// 🦜
console.log(restBirds)
// ["🦢", "🦩", "🐦", "🐧", "🦅", "🦆", "🦉"]
```
Moreover, items in the array being destructured can be skipped.
```js
// skipping 🦢, 🦩, 🐦
let [peacock, parrot, ,,,...restBirds] = ["🦚", "🦜", "🦢", "🦩", "🐦", "🐧", "🦅", "🦆", "🦉"];
console.log(peacock)
// 🦚
console.log(parrot)
// 🦜
console.log(restBirds)
// ["🐧", "🦅", "🦆", "🦉"]
```
#### Array returned from a function
Furthermore, destructuring can make working with an array returned from a function more simpler.
```js
function mamals() {
  return ["🦙", "🦦", "🦧", "🦘"]
}

let [llama, otter, orangutan, kangaroo] = mamals()
console.log(llama)
// 🦙
console.log(otter)
// 🦦
console.log(orangutan)
// 🦧
console.log(kangaroo)
// 🦘

function fruits() {
  return ["🍐", "🥭", "🍑", "🍒"]
}
// skipping 🥭 and 🍑
let [pear,,,cherries] = fruits()
console.log(pear)
// 🍐
console.log(cherries)
// 🍒
```
### Object Destructuring
With ES6, we can use destructuring to assign __object__ values to variables.
#### Basic Object Destructuring
The example below uses the same variables as the keys in the object but you can use a different variable name as well.
```js
const vehicles = {
  car: "🚗",
  taxi: "🚕",
  bus: "🚌",
  minibus: "🚐"
};

const { car, taxi, bus, minibus } = vehicles

console.log(car)
// 🚗
console.log(taxi)
// 🚕
console.log(bus)
// 🚌
console.log(minibus)
// 🚐
```
#### Variable assignment without declaration
```js
let boy, girl;
({boy, girl} = {boy: "👦", girl: "👧"})
```
You probably have noticed the ``( ... )`` around the object literal destructuring assignment without a declaration. This is because the parentheses ``( ... )`` around the assignment statement is required.
```js
let boy, girl;
{boy, girl} = {boy: "👦", girl: "👧"} 
//invalid stand-alone syntax as {boy, girl} is considered a block and not an object literal.

const {boy, girl} = {boy: "👦", girl: "👧"} 
// is a valid syntax
({boy, girl} = {boy: "👦", girl: "👧"}) // is also a valid statement
```
#### Default Values
Default values can be assigned to the variable in a destructuring assignment if the unpacked value from the object is ``undefined``.
```js
const {unicorn = "🦆", eagle = "🦅", chicken = "🐔"} = {unicorn: "🦄"}

console.log(unicorn)
// 🦄
console.log(chicken)
// 🐔
```
Likewise, a property unpacked from an object can be assigned to a variable with a different name.
```js
const balls = {fball: "⚽️", bball: "🏀", sball: "🥎", vball: "🏐"}
const {fball: football, bball: basketball, sball: softball, vball: volleyball} = balls

console.log(football)
// ⚽️
console.log(basketball)
// 🏀
console.log(softball)
// 🥎
console.log(volleyball)
// 🏐
```
Similarly, we can unpack fields from objects passed as a function parameter
```js
const animals = {
  id: 23,
  location: "Madagascar",
  birds: {
    swan: "🦢",
    cockerel: "🐓",
    turkey: "🦃",
    flamingo: "🦩",
    parrot: "🦜"
  },
  mammals: {
    skunk: "🦨",
    raccoon: "🦝",
    kangaroo: "🦘",
    badger: "🦡",
    llama: "🦙"
  }
}

function whereis({location, mammals: {raccoon: image}}){
  return `${image} is located at ${location}`
}

function whichGroup({birds: {swan: bird}, mammals: {badger: mammal}}){
  return `${bird} is a bird and ${mammal} is a mamal`
}

console.log(whereis(animals))
console.log(whichGroup(animals))
```
#### Nested object and array destructuring
We can also destructure a nested object and array.
```js
const animals = {
  id: 23,
  location: "Madagascar",
  birds: [
    {
      swan: "🦢",
      family: "Anatidae",
      genus: "Cygnus"
    }
  ],
  mammals: {
    skunk: "🦨",
    raccoon: "🦝",
    kangaroo: "🦘",
    badger: "🦡",
    llama: "🦙"
  }
}

let {
  location: animalLocation,
  birds: [
    {
      swan: emoji,
      family: animalFamily,
      genus: animalGenus
    }
  ]
} = animals

console.log(animalLocation)
//Madagascar
console.log(emoji)
// 🦢
console.log(animalFamily)
// Anatidae
console.log(animalGenus)
// Cygnus
```
#### Rest in Object Destructuring
Of course, it is possible to use rest in object destructuring. In this case, the rest syntax can be used to collect remaining property keys  that are not already picked off by the destructuring pattern.
```js
const flags = { colombia: "🇨🇴", china: "🇨🇳", cyprus: "🇨🇾", ecuador: "🇪🇨", egypt: "🇪🇬", france: "🇫🇷"}

let {colombia, china, ...restCountries} = flags

console.log(colombia)
// 🇨🇴
console.log(china)
// 🇨🇳
console.log(restCountries)
// { cyprus: "🇨🇾", ecuador: "🇪🇨", egypt: "🇪🇬", france: "🇫🇷"}
```
Finally, with ES6 array and object destructuring, you can do a whole lot. And I believe there is so much to destructuring, so I will appreciate it if you can share in the comment your experience with ES6 destructuring.
### Useful Resources
[Destructuring assignment](https://javascript.info/destructuring-assignment)
[Destructuring assignment - JavaScript \| MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
[ES6 In Depth: Destructuring - Mozilla Hacks - the Web developer blog](https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/)