Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

How do you swap two variables with destructuring?

Do you know what will be the output of this code?

JavaScript
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b);
Show answer and explanation

The answer is 2 1.

The right side creates a new array [2, 1] first, then destructuring assigns its items to a and b.

Take the full quiz Next question →

More Basics questions

  1. Does the spread operator make a deep copy?
  2. When do default parameters apply in JavaScript?
  3. What is the difference between ?? and || in JavaScript?
  4. How does optional chaining short-circuit in JavaScript?
  5. When do destructuring default values apply?

Related topics