ES6 - Destructuring Assignment to Assign Variables from Arrays

I had to look up the answer to this one . Even though it seemed, simple, I wasn’t sure if I was missing something because the exercise didn’t seem to properly match the lesson. When I looked in the forum for discussions, I saw that the exercise used to have a “use strict” bit of code in it. I’m not sure what that was all about, and why FCC changed the exercise (since they are both ES6).

The exercise wants you to destructure an array (assign its items to new names) using an array of new variable names to reassign the items of the original array. But we’re not given an array. If we try to pass the test without using an array, say by coding


the values don’t get swapped because each line is executed in order (not asynchronously, which is a term that doesn’t make linguistic sense, but oh well). So, if you just write a= b then a=b, but b doesn’t =a. And if you write the two lines, as above, a takes on the value of b, so a now = 6. And then b is coded to the value of a, which is now 6. So, we end up with a = 6 and b = 6.

So, we have to use two arrays. And this is where the exercise is unclear. In all the examples, we are given an array to manipulate. We have to realize that, unlike the examples, we are to make this original array. We might think that we could use the numbers for our original array, in which case we would reverse their order so that we could assign them to meet our goal, which is to have a = 6 and b = 8:

[a, b] = [6, 8];

This (above) IS an example of destructuring an array … BUT … the other part of the assignment says “swap the values of a and b”.

SO, to solve this, we have to make the original array, and the tester wants us to use all letters, so it must be: [a, b].

Then, to swap their values, we use destructuring on that array:
[b, a] = [a, b];

If anybody reads this and knows why the old exercise used “use strict” and then that was taken out, I’d love to read your explanation.

My default, the FCC editor uses “use strict” now, so explicitly stating it is redundant.

1 Like

Thank you! That’s exactly what I was wondering. Much appreciated.

1 Like