Skip to content
Devtoolry

Basics · beginner

JavaScript Program to Swap Two Variables

Swap the values of two variables in JavaScript with array destructuring ([a, b] = [b, a]), and with the temporary-variable method used in most languages.

Swapping values is part of sorting algorithms and many small puzzles. Since ES2015, JavaScript can swap two variables in one line with destructuring assignment: the right side builds a temporary array, and the left side unpacks it.

The variables must be declared with let, because a swap assigns new values to them; const would throw a TypeError.

The program

JavaScript
let a = 5;
let b = 10;
console.log("Before:", a, b);

[a, b] = [b, a];
console.log("After:", a, b);
Output
Before: 5 10
After: 10 5

How it works

  1. a and b start as 5 and 10, declared with let so they can change.
  2. [b, a] on the right builds a new array [10, 5] from the current values.
  3. The destructuring pattern [a, b] on the left assigns the first element to a and the second to b.
  4. Because the array was built before anything was assigned, neither value is lost.

Watch it run line by line

On the swap line, a and b change together in a single step. In the temporary-variable version below you can watch temp hold the old value of a for one step.

“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: With a temporary variable

This is the classic three-step swap. It is slightly faster than destructuring in hot loops and easier to translate into other languages.

JavaScript
let a = 5;
let b = 10;
const temp = a;
a = b;
b = temp;
console.log(a, b);
Output
10 5

Common mistakes

  • Starting the swap line with [ right after a line without a semicolon: JavaScript joins the lines and reads console.log(...)[a, b] = …. End the previous line with a semicolon.
  • Declaring the variables with const, which makes the swap throw "Assignment to constant variable".
  • Writing a = b; b = a;, which copies 10 into both variables and loses the 5.

Try it yourself

  • Rotate three variables in one line: [a, b, c] = [b, c, a].
  • Swap two elements of an array: [arr[0], arr[1]] = [arr[1], arr[0]].

Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.