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"
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"
We can also do this with the same result.
var [greeting, pronoun] = ["Hello", "I" , "am", "Sarah"];
console.log(greeting);//"Hello"
console.log(pronoun);//"I"
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"
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"
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"
So the comma separator does the magic. So if we want to skip all items, we just do this.
var [,,,,] = ["Hello", "I" , "am", "Sarah"];
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"]
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"
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"
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
Next, I'll write on Object Destructuring.
Any question or addition? Please leave a comment.
Thank you for reading :)
Latest comments (34)
Thanks. You've rendered to me a lot of help. God bless you.
This is an awesome and very thorough explanation of destructuring assignment. Thanks!
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
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
you should find that you get the expected result. The following also works:
However, without a semicolon after the 7, or the enclosing braces, it is somehow interpreted as
great article!
Thank you so much for this, it comes handy.
Thank you Sarah, you made so easy to understand.
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}
It might be worth mentioning that the syntax used in code below is also called JavaScript rest parameter syntax, specifically the
...intro
part,This is awesome. Thank you, Sarah :-)
What if you want to swap the variables inside a function? Something like this:
console.log(a)
console.log(b)
Do share your suggestions on this.
There is no need to call a function it will work without calling function.
var a = 3;
var b = 6;
[a,b] = [b,a]
Hi Ashley, I just tried the code now and it works as expected. Did you try printing the values of key and rowValues?
It does for me too now. /facepalm and thank you
I'll delete my original post to avoid confusing any one
Thank you for posting the article. It helped me understand Destructuring assignment.
You just impacted one more person with knowledge, thank you Sarah.
awesome..thank you sarah
great post, thanks.