How to Quickly Swap Two Variables in JavaScript
Last updated on August 20, 2022

Every Crazy Thing JavaScript Does

Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.
1. Temporary Variable
To swap two variables in JavaScript:
- Create a temporary variable to store the value of the first variable
- Set the first element to the value of the second variable.
- Set the second variable to the value in the temporary variable.
For example:
let a = 1;
let b = 4;
// Swap variables
let temp = a;
a = b;
b = temp;
console.log(a); // 4
console.log(b); // 1
2. Array Destructuring Assignment
In ES6+ JavaScript we can swap two variables with this method:
- Create a new array, containing both variables in a particular order.
- Use the JavaScript array destructing syntax to unpack the values from the array into a new array that contains both variables in a reversed order.
With this method, we can create a concise one-liner to do the job.
let a = 1;
let b = 4;
[a, b] = [b, a];
console.log(a); // 4
console.log(b); // 1
11 Amazing New Features in ES13

Get up to speed with all the latest features added in ECMAScript 13 to modernize your JavaScript with shorter and more expressive code.
See also
- How to quickly get the union of two Sets in JavaScript
- How to quickly get the union of two arrays in JavaScript
- How to get the difference between two arrays in JavaScript
- How to get the difference between two sets in JavaScript
- How to easily get the intersection of two sets in JavaScript
- How to Get the Number of Months Between Two Dates in JavaScript