DEV Community

Sarah Chima
Sarah Chima

Posted on

Destructuring Assignment in ES6- Arrays

Destructuring assignment is a cool feature that came along with ES6. Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables. Why is this necessary?

Imagine if we want extract a data from an array. Previously, how will this be done?


    var introduction = ["Hello", "I" , "am", "Sarah"];
    var greeting = introduction[0];
    var name = introduction[3];

    console.log(greeting);//"Hello"
    console.log(name);//"Sarah"
Enter fullscreen mode Exit fullscreen mode

We can see that when we want to extract data from an array , we had to do the same thing over and over again. ES6 destucturing assignment makes it easier to extract this data. How is this so? This article discusses destructuring assignment of arrays. My next article will discuss that of objects. Let's get started.

Basic Destructuring

If we want to extract data using arrays, it's quite simple using destructuring assignment. Let's refer to our first example for arrays. Instead of going through that repetitive process, we'll do this.


    var introduction = ["Hello", "I" , "am", "Sarah"];
    var [greeting, pronoun] = introduction;

    console.log(greeting);//"Hello"
    console.log(pronoun);//"I"

Enter fullscreen mode Exit fullscreen mode

We can also do this with the same result.

    var [greeting, pronoun] = ["Hello", "I" , "am", "Sarah"];

    console.log(greeting);//"Hello"
    console.log(pronoun);//"I"

Enter fullscreen mode Exit fullscreen mode

Declaring Variables before Assingment
The variables can be declared before being assigned like this.


    var greeting, pronoun;
    [greeting, pronoun] = ["Hello", "I" , "am", "Sarah"];

    console.log(greeting);//"Hello"
    console.log(pronoun);//"I"

Enter fullscreen mode Exit fullscreen mode

Notice that the variables are set from left to right. So the first variable gets the first item in the array, the second variable gets the second variable in the array and so on.

Skipping Items in an Array

What if we want to get the first and last item on our array instead of the first and second item and we want to assign only two variables? This can also be done. Look at the example below.

    var [greeting,,,name] = ["Hello", "I" , "am", "Sarah"];

    console.log(greeting);//"Hello"
    console.log(name);//"Sarah"

Enter fullscreen mode Exit fullscreen mode

What just happened? Look at the array on the left side of the variable assignment. Notice that instead of having just one comma, we had three. The comma separator is used to skip values in an array. So if you want to skip an item on an array, just use a comma.

Let's do another one. I think it's fun. Let's skip the first and third item on the list. How will we do this?

    var [,pronoun,,name] = ["Hello", "I" , "am", "Sarah"];

    console.log(pronoun);//"I"
    console.log(name);//"Sarah"

Enter fullscreen mode Exit fullscreen mode

So the comma separator does the magic. So if we want to skip all items, we just do this.

    var [,,,,] = ["Hello", "I" , "am", "Sarah"];

Enter fullscreen mode Exit fullscreen mode

Assigning the rest of an array

What if we want to assign some of the array to variables and the rest of the items on an array to a particular variable? We'll do this.

    var [greeting,...intro] = ["Hello", "I" , "am", "Sarah"];

    console.log(greeting);//"Hello"
    console.log(intro);//["I", "am", "Sarah"]

Enter fullscreen mode Exit fullscreen mode

Using this pattern, you can unpack and assign the remaining part of an array to a variable.

Destructuring Assignment with Functions
We can also extract data from an array returned from a function. Let's say we have a function that returns an array like the example below.

    function getArray() {
        return ["Hello", "I" , "am", "Sarah"];
    } 
    var[greeting,pronoun] = getArray();

    console.log(greeting);//"Hello"
    console.log(pronoun);//"I"
Enter fullscreen mode Exit fullscreen mode

We get the same results.

Using Default Values
Default values can be assigned to the variables just in case the value extracted from the array is undefined.


    var[greeting = "hi",name = "Sarah"] = ["hello"];

    console.log(greeting);//"Hello"
    console.log(name);//"Sarah"
Enter fullscreen mode Exit fullscreen mode

So name falls back to "Sarah" because it is not defined in the array.

Swapping Values using Destructuring Assignment
One more thing. We can use destructuring assignment to swap the values of variables.

    var a = 3;
    var b = 6;

    [a,b] = [b,a];

    console.log(a);//6
    console.log(b);//3
Enter fullscreen mode Exit fullscreen mode

Next, I'll write on Object Destructuring.

Any question or addition? Please leave a comment.

Thank you for reading :)

Latest comments (34)

Collapse
 
keithv978 profile image
KeithV978

Thanks. You've rendered to me a lot of help. God bless you.

Collapse
 
iamtheiam profile image
IAMtheIAM

This is an awesome and very thorough explanation of destructuring assignment. Thanks!

Collapse
 
uchennaanya profile image
Anya Uchenna

please I am still learning JS I tried out swapping with destructuring it didn't work i don't know why here is the code var a = 3
var b = 7
[a, b] = [b, a]

a

Collapse
 
jwm63ara profile image
jwm63ara

Hi Anya,

I'm still learning too, so I don't fully understand this, but it is an example of a situation where automatic semicolon insertion doesn't work the way you might expect. If you try

var a = 3
var b = 7;
[a, b] = [b, a]

you should find that you get the expected result. The following also works:

var a = 3
var b = 7
{
  [a, b] = [b, a]
}

console.log(a)   // expect 7
console.log(b)   // expect 3

However, without a semicolon after the 7, or the enclosing braces, it is somehow interpreted as

var a = 3
var b = [b, a]

console.log(a)   // expect 3
console.log(b)   // expect [undefined, 3]
Collapse
 
kanavsharma1 profile image
kanavsharma1

great article!

Collapse
 
omobolarinwa profile image
Luqman Abdulwasii

Thank you so much for this, it comes handy.

Collapse
 
hamicch profile image
Hayatu Sanusi

Thank you Sarah, you made so easy to understand.

Collapse
 
tiruvengadam85 profile image
Tiruvengadam85

Hi I have an array item which conatains nested object, how to destructure 0: {applied_rule_ids: "XXX", base_currency_code: "AED", base_discount_amount: -310, base_grand_total: 300, base_discount_tax_compensation_amount: 14.78}
1: {applied_rule_ids: "YYY", base_currency_code: "AED", base_discount_amount: 0, base_grand_total: 170, base_discount_tax_compensation_amount: 0}
2: {base_currency_code: "AED", base_discount_amount: 0, base_discount_invoiced: 0, base_grand_total: 50, base_discount_tax_compensation_amount: 0}
3: {base_currency_code: "AED", base_discount_amount: 0, base_discount_invoiced: 0, base_grand_total: 100, base_discount_tax_compensation_amount: 0}

Collapse
 
joquijada profile image
Jose Quijada • Edited

It might be worth mentioning that the syntax used in code below is also called JavaScript rest parameter syntax, specifically the ...intro part,

var [greeting,...intro] = ["Hello", "I" , "am", "Sarah"];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ashekhawat32 profile image
IamLegendChamp

This is awesome. Thank you, Sarah :-)

Collapse
 
manish169 profile image
Manish

What if you want to swap the variables inside a function? Something like this:

var a = 3;
var b = 6;

(() => {
  [a,b] = [b,a]
})()
Enter fullscreen mode Exit fullscreen mode

console.log(a)
console.log(b)

Do share your suggestions on this.

Collapse
 
aquifzubair profile image
aquifzubair

There is no need to call a function it will work without calling function.

var a = 3;
var b = 6;
[a,b] = [b,a]

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
sarah_chima profile image
Sarah Chima

Hi Ashley, I just tried the code now and it works as expected. Did you try printing the values of key and rowValues?

Collapse
 
ashleyo profile image
Ashley Oliver • Edited

It does for me too now. /facepalm and thank you
I'll delete my original post to avoid confusing any one

Collapse
 
cyril_thankgod profile image
Cyril ThankGod

Thank you for posting the article. It helped me understand Destructuring assignment.

Collapse
 
evuazeze profile image
evuazeze

You just impacted one more person with knowledge, thank you Sarah.

Collapse
 
nirajthing profile image
Niraj Thing

awesome..thank you sarah

Collapse
 
mekaeil profile image
Mekaeil

great post, thanks.