DEV Community

Destructuring Assignment in ES6- Arrays

Sarah Chima on October 30, 2017

Destructuring assignment is a cool feature that came along with ES6. Destructuring is a JavaScript expression that makes it possible to unpack valu...
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!

Collapse
 
evuazeze profile image
evuazeze

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

Collapse
 
ashekhawat32 profile image
IamLegendChamp

This is awesome. Thank you, Sarah :-)

Collapse
 
nirajthing profile image
Niraj Thing

awesome..thank you sarah

Collapse
 
sgharms profile image
Steven G. Harms

I get into ruts of use it's nice to remember and see others' patterns. Well done.

Collapse
 
kanavsharma1 profile image
kanavsharma1

great article!

Collapse
 
mekaeil profile image
Mekaeil

great post, thanks.

Collapse
 
cyril_thankgod profile image
Cyril ThankGod

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

Collapse
 
keithv978 profile image
KeithV978

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

Collapse
 
seamanb2k profile image
DigitalEmma

Thank you for the informative piece, very explanatory was using this alongside a video tutorial on the subject matter, your example were easy to understand.

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you for reading it

Collapse
 
omobolarinwa profile image
Luqman Abdulwasii

Thank you so much for this, it comes handy.

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
 
hamicch profile image
Hayatu Sanusi

Thank you Sarah, you made so easy to understand.