To swap two numbers means exchange their values: after the swap, the first variable holds what the second had, and the second holds what the first had.
Remember
Before: a = 5, b = 10
After: a = 10, b = 5
Interview default:
temp = a
a = b
b = temp
Modern JS:
[a, b] = [b, a]
Method
Idea
Notes
Temp variable
Save, overwrite, restore
Clearest interview answer
Destructuring
[a, b] = [b, a]
Idiomatic modern JavaScript
XOR
Three ^= steps
Integers only; interview trick
Approach
How to Swap Two Numbers in JavaScript
Four clear steps for the temp method — then modern and no-temp variants.
Store the first value in temp.
Copy the second value into the first variable.
Copy temp into the second variable.
Or show destructuring / XOR as alternatives when asked.
Method
Idea
Time
Best for
Temp variable
temp = a; a = b; b = temp;
O(1)
Interviews, any language
Destructuring
[a, b] = [b, a]
O(1)
Everyday JavaScript
XOR
a ^= b three times
O(1)
Integer bit trick
Pseudocode
Pseudocode
function SwapTemp(a, b):
temp = a
a = b
b = temp
return a, b
function SwapDestructure(a, b):
[a, b] = [b, a]
return a, b
function SwapXor(a, b):
if a != b:
a = a XOR b
b = b XOR a
a = a XOR b
return a, b
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Default
Use a temporary variable
Temp steps
temp = a; a = b; b = temp;
Modern JS
[a, b] = [b, a]
Equal values
Swap still works; result unchanged
XOR
Integers only; optional trick
Classic check
5, 10 → 10, 5
Try it
Live Preview
Enter two integers and swap them with the temporary-variable method.
Whole numbers only. Tap a chip or type a pair.
Result
Before: a = 5, b = 10
temp = 5
a = 10
b = 5
After: a = 10, b = 5
Code
JavaScript Programs
Start with a temporary variable — the interview default. Then show destructuring as the modern JS form, and XOR as a no-temp trick. Each example has a Try it Yourself editor.
Example 1 — Swap Using Temp Variable
Save the first value, overwrite it, then restore into the second variable.
Before swapping: num1 = 5, num2 = 10
After swapping: num1 = 10, num2 = 5
How It Works
The right side builds [10, 5] from the current values.
The left side unpacks that array into num1 and num2.
No named temp — the array is a short-lived temporary.
Works for strings, objects, and any assignable values — not just numbers.
Prefer this in everyday JavaScript; still mention temp in interviews.
Example 3 — Swap Without Temp (XOR Trick)
Three XOR steps trade bit patterns. Keep it as an interview curiosity.
JavaScript
let a = 5;
let b = 10;
console.log("Before swapping: a = " + a + ", b = " + b);
if (a !== b) {
a ^= b;
b ^= a;
a ^= b;
}
console.log("After swapping: a = " + a + ", b = " + b);