DEV Community

Jonathan Cohen
Jonathan Cohen

Posted on

Destructuring Assignment

This past week I was going over destructuring in JS. It's still a bit foggy to me but I think I have more of a grasp on it than I did when I first started my review. I'll share some of what I learned. Before we begin let's create an array to use as an example as we destructure.

let yuna = ["Valefor", "Ifrit", "Ixion", "Shiva", "Bahumaut"
]

Here we have the summoner Yuna with her all of her aeons to take with her in the final fight placed into the array. Yuna has the possibility to assign a variable(give a nickname) to her favorite aeon that's inside the array. How could she do that specifically for her favorite aeon. She could use destructuring on an array to assign the variable. Let's see that in action:

const yuna = ["Valefor", "Ifrit", "Ixion", "Shiva", "Bahumaut"];

const [favorite] = yuna
console.log(favorite)
//console will log Valefor

Enter fullscreen mode Exit fullscreen mode

Amazing right? That was clean and the other aeons don't know a thing about it. So exactly happened? It seems like a pretty confusing variable assignment at first glance but this code is the same if it was written as:

const yuna = ["Valefor", "Ifrit", "Ixion", "Shiva", "Bahumaut"];

const favorite = yuna[0]
console.log(favorite)
//console will log Valefor

Enter fullscreen mode Exit fullscreen mode

Could we destructure even further into the array? We can.

const yuna = ["Valefor", "Ifrit", "Ixion", "Shiva", "Bahumaut"];

const [favorite, scariest] = yuna
console.log(favorite, scariest)
//console will log Valefor,Ifrit

Enter fullscreen mode Exit fullscreen mode

Which would be the same as writing:

const yuna = ["Valefor", "Ifrit", "Ixion", "Shiva", "Bahumaut"];

const favorite = yuna[0]
const scariest = yuna[1]
console.log(favorite,scariest)
//console will log Valefor, Ifrit

Enter fullscreen mode Exit fullscreen mode

Simple right? Code like this could clean up alot of variable assignments within the script. The rabbit hole of destructuring goes deep. My plan is to next practice with destructuring objects. I'll report back my findings.

Top comments (0)