JavaScriptQuestion 27 of 36
Task: swapping values
Answer out loud or in your head first, then compare.
Answer
Destructuring lets you swap values without a separate helper variable.
JavaScript
let a = 10;
let b = 20;
[a, b] = [b, a];
console.log(a, b); // 20, 10To be precise: the right-hand side is evaluated before the assignment on the left. The variables must allow reassignment.
Pitfall: solutions using addition or XOR are limited by types and number ranges. Destructuring is more readable and works for other values too.
How did it go? Be honest — “Not yet” puts the question on your review list.