How to Swap Variables Using Destructuring in JavaScript
You can swap variables in JavaScript using
destructuring assignment by placing the variables inside an array on both sides of the assignment, like [a, b] = [b, a]. This swaps the values without needing a temporary variable.Syntax
The syntax for swapping two variables a and b using destructuring is:
[a, b]on the left side represents the variables to assign values to.[b, a]on the right side creates an array with the values in swapped order.- The assignment swaps the values of
aandbin one step.
javascript
[a, b] = [b, a];
Example
This example shows swapping two variables a and b using destructuring. It prints the values before and after swapping.
javascript
let a = 5; let b = 10; console.log('Before swap:', a, b); [a, b] = [b, a]; console.log('After swap:', a, b);
Output
Before swap: 5 10
After swap: 10 5
Common Pitfalls
Common mistakes when swapping variables include:
- Trying to swap without destructuring, which requires a temporary variable.
- Using incorrect syntax like
a = b; b = a;which does not swap correctly. - Forgetting to use array brackets
[]on both sides.
Always use the array destructuring syntax to swap safely and clearly.
javascript
let a = 1; let b = 2; // Wrong way - does not swap correctly // a = b; // b = a; // Right way [a, b] = [b, a];
Quick Reference
Remember these tips for swapping variables with destructuring:
- Use
[a, b] = [b, a]to swap two variables. - No temporary variable needed.
- Works with any variable types (numbers, strings, objects).
- Clean and readable syntax.
Key Takeaways
Use array destructuring syntax [a, b] = [b, a] to swap variables in one line.
No need for a temporary variable when swapping with destructuring.
Ensure to use brackets [] on both sides for correct syntax.
This method works for any variable types, making code cleaner and easier to read.