Destructuring Arrays or Variables?

Tell us what’s happening:

I have solved this challenge after some Read-Search-Ask but what I don’t understand is why the destructuring assignment works in this case since it is supposed to work only with Arrays? And a and b are not elements of an Array, so how come this assignment works?

Your code so far

SPOILER ALERT: solution below


let a = 8, b = 6;
// Only change code below this line
[a, b] = [b, a];

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36.

Challenge: Use Destructuring Assignment to Assign Variables from Arrays

Link to the challenge:

you create an array in place writing [b, a], so that’s an arrayi with two elements, so on the right hand side you have an array, on the left hand side you can use destructuring

works the same if you do

let arr = [b, a];
[a, b] = arr;

(but with this you can’t pass the challenge)


Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

2 Likes

Will do, thank you for the explanation and for the instruction on how to blur out spoilers :ok_hand: