ES6 Array destructing

Tell us what’s happening:

I don’t understand how to use array destruction to swap a and b

Your code so far

let a = 8, b = 6;
// Only change code below this line
[a, b] = [6, 8]
console.log(a , b)

Your browser information:

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

Challenge: Use Destructuring Assignment to Assign Variables from Arrays

Link to the challenge:

here you have written in the numbers, but what about if you don’t know the values of the variables? it’s not much different than this

I don’t understand what you are trying to mean

a is going to be the value of b and b is going to be the value of a. So a is going to be b and b is going to be a. So you are trying to assign b to a and a to b. So…

what I don’t exactly get is how I can use array destructing to swap the values of a and b.
so please how can I do that?

You’ve said the value of a is is literally 6 and the value of b is literally 8. But you want to do is say the value of a is b and the value of b is a

I have got you
Thanks buddy

1 Like

It’s a little bit hard to grok at first, but once it clicks the syntax should be quite clear.

The actual task (swapping variables) is not something that needs to be done very often, but it’s a common example problem because it shows how destructuring can make clear what’s happening. To swap two variables without destructuring:

let a = 6;
let b = 8;
let temp;

temp = a; // make sure don't lose a
a = b; // now they are both 8
b = temp; // now b is 6

With destructuring, you just say a is b and b is a, there’s no need to use a temporary variable