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.
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:
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.
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.
let pie, cupcake;
[pie, cupcake] = ['π₯§', 'π§']
console.log(pie)
// π₯§
console.log(cupcake)
// π§
Variable Swap
Again, we can swap two variables in a single destructuring expression.
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
let [peacock, parrot, ...restBirds] = ["π¦", "π¦", "π¦’", "π¦©", "π¦", "π§", "π¦
", "π¦", "π¦"];
console.log(peacock)
// π¦
console.log(parrot)
// π¦
console.log(restBirds)
// ["π¦’", "π¦©", "π¦", "π§", "π¦
", "π¦", "π¦"]
Moreover, items in the array being destructured can be skipped.
// 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.
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.
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
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.
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
.
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.
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
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.
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.
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
Destructuring assignment - JavaScript | MDN
ES6 In Depth: Destructuring - Mozilla Hacks - the Web developer blog
Top comments (0)