Array Destructuring in Javascript

Array Destructuring in Javascript

ยท

2 min read

Introduced in ES6, destructuring in simple words is a way to decompose a structure into individual parts. It's an effort to move from the traditional imperative approach to a declarative approach that allows us to write more readable code which reflects the pattern that we want to see. Let me show you what that means by an example. Imagine you have a huge complex data structure coming from an API and you are only interested in a few properties. Now let's do that using both approaches.

// imperative style
const quotes = api();

// I only want the first two elements from the quotes array
let a = quotes[0];
let b = quotes[1];

let firstQuote = a.quote;
let firstAuthor = a.author;

let secondQuote = b.quote;
let secondAuthor = b.author;

Here's how we would write the same code using destructuring:

// declarative style

let [
    {
        quote: firstQuote,
        author: firstAuthor
    },
    {
        quote: SecondQuote,
        author: SecondAuthor
    }
] = api();

If you look at both styles, you will find the declarative one more readable because it's literally describing what we excepted to get from the api(). This is how destructuring unpacks values that you care about into distinct variables.

Let's look at another example. Imagine we have an array of avengers. (Yeah, I'm a nerd ๐Ÿ˜)

const avengers = [
    'Iron Man',
    'Thor',
    'Captain America',
    'Hulk',
    'Black Widow',
    'Hawkeye'
]

Now, let's assign them to some variables.

// without destructuring

let everyonesFav = avengers[0];
let whoWentForTheHead = avengers[1];
let others = avengers.slice(2);

With destructuring, we can achieve the same but with more readable & self-documenting code

let [
    everyonesFav,
    whoWentForTheHead,
    ...others
] = avengers;

To achieve the slice effect, We use rest operator i.e, a variable name having three dots as a prefix.

In both examples, everyonesFav is Iron Man, whoWentForTheHead is Thor, and others is ['Captain America', 'Hulk', 'Black Widow', 'Hawkeye']

That's all with the basics of array destructuring in javascript. In the next article, we will learn about object destructuring & more on destructuring in general.