-4

I am revising JavaScript and came to following ES6 example.

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

Not able to figure out how this is working, as we have assignment operator with both side arrays.

Amol Patil
  • 985
  • 2
  • 11
  • 43

1 Answers1

1

Destructuring basically separates an array or an object into separate variables. That is what happens on the left side. Exemple:

var foo = [1, 2]
var [a, b] = foo; // creates new variables a and b with values from the array foo

console.log(a); // prints "1"
console.log(b); // prints "2"

On the right side, you are creating an array with the values [b, a] which will be destructured. As a result, the two variables are switched.

Luke
  • 565
  • 5
  • 19