Course contentsShow
← JavaScript
Lesson 921 of 2,72321. DestructuringFree lesson

Swapping Variables Without a Temp

Using array destructuring to elegantly swap variable values in a single statement.

Swapping Variables Without a Temp

What you'll learn: How to use array destructuring to swap two variables in a single, elegant line without needing a temporary variable.

The Old Way vs. The New Way

Traditionally, swapping two variables required a temporary "holding" variable:

let a = 5;
let b = 10;

// Old approach: need a temp variable
let temp = a;
a = b;
b = temp;

console.log(a); // 10
console.log(b); // 5

This works, but it's verbose and requires an extra variable cluttering your code.

Array Destructuring to the Rescue

With array destructuring, you can swap values in one beautiful line:

let a = 5;
let b = 10;

[a, b] = [b, a];

console.log(a); // 10
console.log(b); // 5

How It Works

Think of it like this: you're creating a temporary array [b, a] on the right side with the values in swapped order, then immediately destructuring it back into a and b on the left side.

The right side evaluates first, capturing both current values, then the left side unpacks them into the variables. No temp variable needed—JavaScript handles it internally!

Works with Any Variables

let first = "hello";
let second = "world";

[first, second] = [second, first];

console.log(first);  // "world"
console.log(second); // "hello"

Multiple Swaps

You can even extend this pattern:

let x = 1, y = 2, z = 3;

[x, y, z] = [z, x, y]; // Rotate all three

console.log(x, y, z); // 3 1 2

Key Takeaway: Array destructuring lets you swap variables in one line: [a, b] = [b, a], eliminating the need for temporary variables and making your code cleaner and more readable.