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 :)

Top comments (34)

Collapse
 
karfau profile image
Christian Bewernitz • Edited

Tank you for posting, didn't know about this way of skipping elements.

But the following sentence might be misleading (if it wouldn't be for the headline above):

What if we want to get the first and last item on the array...?

The way you show is really only working if you know the size of the array, which obviously you don't always do, e.g. when destructing an argument inside a function.

If you don't know it, you could do the following without touching the initial array:

const input = ["Hello", "I" , "am", "Sarah"];
const [greeting, ...rest] = input;
//rest == ["I" , "am", "Sarah"]
const name = rest.pop(); // rest is modified but input isn't
//or if you prefer or need more then one from the end
const [last, secondLast] = rest.reverse(); // rest is modified!
Enter fullscreen mode Exit fullscreen mode

The ...name must always be the last part, so const [greeting, ...dontCare, name] = ... does not work.

We should also mention how destructing works when encountering [] and undefined:

var [a, b, ...rest] = [];
console.log(a,b,rest);//undefined, undefined, []

var [ouch] = undefined;//Uncaught TypeError: undefined is not iterable
Enter fullscreen mode Exit fullscreen mode

Hm, iterable? What happens if we destruct some other iterable?

var [a, b, ...rest] = "abc,d";
console.log(a, b, rest);//"a", "b", ["c", ",", "d"]
Enter fullscreen mode Exit fullscreen mode

Happy coding!

Collapse
 
ramachintaguntla profile image
ramachintaguntla

I dint know that even string could be destructed.. i was under the impression that only Array and Objects can be done.. are there any others that can be destructed?(other than strings, objects, arrays)

Collapse
 
sayopaul profile image
Sayo Paul

Wow . Thank you so much for this

Collapse
 
viricruz profile image
ViriCruz

Thank you for explaining this in an understandable human way!. It was very easy to digest and helpful.

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
 
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
 
kodekage profile image
Prosper Opara

This is an awesome piece..

I have some questions

let [greet = "hello world", name = "sarah"] = ["hello"];

console.log(greet); // returns "hello"

why is is overriding the default value assigned to hello?

Collapse
 
sayopaul profile image
Sayo Paul

I am not sure I understand your question fully but like the article explains , in this case , the array contains one element , "hello" and thus it overrides the default value of the first variable greet whilst the second variable is its default value as the array doesn't have a second element πŸ™‚ .

Collapse
 
malvinjay profile image
George Arthur

I think the question isn't that clear. Variables available are 'greet' and 'name' to which they both have default values. However, "greet" is assigned a value from Destructuring and thus will now return that value i.e ("hello") instead of it's default value give at initialization.

Collapse
 
shrijan00003 profile image
Shrijan

greet = "hello world" is just a default value , if there is the value in first element in parent array then it will get overridden for sure. That is what default value is made for.

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
 
yogesh_cbe profile image
Yogesh S

I just started learning JavaScript. I was not able to follow Destructuring in JavaScript. Your explanation and the examples were very simple and easy to understand. Thank you very much for posting such a great article.

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you for your kind words. I am glad you like the article.

Collapse
 
deepankar14693 profile image
deepankar14693 • Edited

Very nicely explained. Can you tell what is happening in below code :

case Actions.AC_UPDATE_TASK:
item = action.payload.item;
props = action.payload.props;
item.start = props.start ? props.start : item.start;
item.end = props.end ? props.end : item.end;
item.name = props.name ? props.name : item.name;
return {
data: [...state.data],
links: [...state.links],
selectedItem: state.selectedItem
};

Here item and props are coming as parameter,item is present there in data array. After manipulating item from props this item needs to be updated in data array but here its not updated in data array after manipulating it. But after destructuring syntax I can see the updated item in data array. How is this possible?

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
 
tai8292 profile image
tai8292

Thank you for posting, it's very helpfull

Collapse
 
iamtheiam profile image
IAMtheIAM

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