[b,a]? -- Destructuring Assignment to Assign Variables from Arrays

Tell us what’s happening:

My code works, but I needed the hint, and still don’t fully understand what’s going on here:

[b,a] = [a,b];

As I understand destructuring assignment, it unpacks arrays, but no array up to this point has been created. Are we creating an “anonymous array”, if there is such a thing, simply by enclosing the two declared variables in square brackets on the left of the =?

Also, why doesn’t "use strict"; break this? Aren’t we creating a new array with the [b,a] = code?

Thanks,

Your code so far


let a = 8, b = 6;
(() => {
  "use strict";
  // change code below this line
  
  [b,a] = [a,b]

  // change code above this line
})();
console.log(a); // should be 6
console.log(b); // should be 8

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays

There isn’t an array on the left hand side. On the right hand side the variables a and b have been put in an array.

On the left hand side, you can do a form of pattern matching (like in a regex) against the values being assigned on the right: if the pattern on the left matches the pattern on the right, the values in the object on the right are assigned to the variables on the left. The [b, a] on the left is two variable names, but you can’t just have b, a = a, b, JS doesn’t allow that syntax (compare with Python, which does), you have to put them in a container on the right hand side, and specify the shape on the left.

This challenge is a slightly special case, usage normally looks more like:

const [a, b] = [1, 2]

// Same as
const a = 1
const b = 2

In this case, it kinda is the same as:

[a, b] = [b, a]

// Sort of the same as
a = b
b = a

But this can’t actually work without the destructuring syntax. Once a gets assigned b’s value, both have the same value and a’s original is lost. So, previously to swap var, you needed to do:

// assign the value of a to a temporary variable
let temp = a
// assign the value of b to a, a and b are now the same
a = b
// assign temp (the previous a value) to b
b = temp

Dan, Thanks very much. The syntax of the solution to the challenge was so terse, it was hard to see where the moving parts were. Your reply explained a lot.