Temp Variable
Classic
Save, overwrite, restore.
Swapping exchanges two variables so each holds the other’s old value: a=5, b=10 becomes a=10, b=5. You will use a temp variable, JavaScript’s [a, b] = [b, a], and an optional XOR trick for integers — plus a live preview and worked examples.
Classic
Save, overwrite, restore.
[a, b] = [b, a]
The idiomatic JavaScript everyday swap.
Integers
Interview curiosity, not style.
Order
Save before you overwrite.
Try 5 & 10
Swap custom integers instantly.
All variants
Constant time and space.
Swapping means exchanging the values of two variables without losing either one. If you write a = b first, the old a is gone forever — that is why beginners learn a temporary holder.
In JavaScript you can skip the explicit temp with destructuring: [a, b] = [b, a]. Interviews still like the classic three-step swap because it transfers to C, Java, and sorting algorithms.
Swap is a building block for sorting, partitioning, and many in-place algorithms.
temp holds a copy.
[a, b] = [b, a]
Integers only.
7, 7 stays 7, 7.
In short: exchange values without losing either — prefer [a, b] = [b, a] in JavaScript.
Given two variables, exchange their values so each holds what the other used to hold.
# Before: a = 5, b = 10
# After: a = 10, b = 5 | Item | Type | Description |
|---|---|---|
a, b | any / int | Values to exchange (XOR needs ints). |
| Result | same types | a holds old b; b holds old a. |
temp | same as a | Optional holding spot. |
temp = a
a = b
b = temp | Method | Idea | Notes |
|---|---|---|
| Temp variable | Save, overwrite, restore | Universal across languages |
| Destructuring | [a, b] = [b, a] | Preferred in JavaScript |
| XOR | a ^= b; b ^= a; a ^= b | Integers; interview trick |
| Goal | Pattern |
|---|---|
| Temp save | temp = a |
| Overwrite | a = b |
| Restore | b = temp |
| idiomatic JavaScript | [a, b] = [b, a] |
| XOR (ints) | a ^= b; b ^= a; a ^= b |
| Equal values | Swap still correct; no visible change |
Same result — different packaging.
temp = aClearest cross-language idea
[a, b] = [b, a]Everyday JavaScript style
a ^= bIntegers only; less readable
a = b firstLoses the old a
Reach for a swap whenever two values need to trade places in place.
First assignment / memory drill.
Bubble / selection / partition swaps.
arr[i], arr[j] = arr[j], arr[i]
Temp swap proves shared concepts.
Stick to temp or destructuring then.
Key benefit: one tiny idea — save before overwrite — that shows up in almost every in-place algorithm.
Enter two integers and swap them with a temporary variable.
Three complete JavaScript programs — temp variable, destructuring, and XOR for integers. Click View Output to reveal sample console results.
The classic three-step swap that works in almost every language.
Save the first value, overwrite it, then restore into the second variable.
let num1 = 5;
let num2 = 10;
console.log(`Before swapping: num1 = ${num1}, num2 = ${num2}`);
const temp = num1;
num1 = num2;
num2 = temp;
console.log(`After swapping: num1 = ${num1}, num2 = ${num2}`); temp keeps 5 while num1 becomes 10. Then num2 receives the saved 5.
Destructuring does the same exchange in one line.
Preferred everyday style in JavaScript. The right-hand side builds a temporary pair first.
let num1 = 5;
let num2 = 10;
console.log(`Before swapping: num1 = ${num1}, num2 = ${num2}`);
[num1, num2] = [num2, num1];
console.log(`After swapping: num1 = ${num1}, num2 = ${num2}`); JavaScript evaluates [num2, num1] first, then unpacks into num1 and num2. No explicit temp name is needed.
Works for integers. Prefer destructuring in real JavaScript code; keep XOR as an interview curiosity.
let a = 5;
let b = 10;
if (a !== b) {
a ^= b;
b ^= a;
a ^= b;
}
console.log(`After swapping: a = ${a}, b = ${b}`); Three XOR steps rearrange the bit patterns so a and b trade places. The a !== b guard avoids a known edge when both aliases point at the same location in some languages; for plain JavaScript ints it is still a good habit to mention.
Save the first value.
Copy the second into the first.
Restore the saved value into b.
Neither original was lost.
Follow the temp variable through each assignment.
| Step | a | b | temp |
|---|---|---|---|
| start | 5 | 10 | — |
| temp = a | 5 | 10 | 5 |
| a = b | 10 | 10 | 5 |
| b = temp | 10 | 5 | 5 |
If you assign a = b first without saving, the original 5 disappears.
Where swaps show up beyond the interview prompt.
Assignment and memory basics.
Example: temp swap of 5, 10.
Bubble and selection swaps.
Example: adjacent pairs.
arr[i], arr[j] = arr[j], arr[i]
Example: in-place reorder.
Quicksort-style exchanges.
Example: pivot swaps.
Why overwrite order matters.
Example: walkthrough table.
Continue the interview chain.
Example: related CTA.
Pro Tip: say “save before overwrite” before you write the three lines.
Why learning all three approaches is useful.
Same idea in C, Java, JS, and more.
One line, hard to get wrong in JavaScript.
O(1) time and space for all variants.
Useful trivia once you know the readable form.
Pro Tip: lead with temp or destructuring; mention XOR only if asked about “without a temp”.
Small habits that keep swap solutions interview-ready.
Never a = b as the first step alone.
[a, b] = [b, a] for production code.
Makes demos and debugging clearer.
Integers only; mention readability cost.
7, 7 should remain 7, 7.
Pro Tip: sanity-check (5, 10), (7, 7), and (-4, 20) — if those three work, you are solid.
Mistakes that commonly break swap programs.
Writing a = b without saving a.
→ Use temp or destructuring.
Floats and strings do not XOR.
→ Use temp or destructuring instead.
Missing one of the three ^= steps.
→ Prefer [a, b] = [b, a] in JavaScript.
Expecting failure when a == b.
→ Swap is still correct.
Clever but harder to maintain.
→ Use the readable form.
Handle these before claiming the swap is complete.
Swap is still correct.
Destructuring swap is preferred in JavaScript.
-4 and 20 swap fine.
0, 3 becomes 3, 0.
Skip XOR.
arr[i], arr[j] = arr[j], arr[i]
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
[a, b] = [b, a].Quick Takeaway: save before overwrite — or write [a, b] = [b, a].
| Version | Time | Extra space |
|---|---|---|
| Temp swap | O(1) | O(1) |
| Destructuring swap | O(1) | O(1) |
| XOR swap | O(1) | O(1) |
Swapping two variables does a fixed number of assignments regardless of the values.
Swapping exchanges two values without losing either one. Learn the temp-variable pattern for every language, prefer [a, b] = [b, a] in JavaScript, and treat XOR as optional trivia.
Practice the three examples above, then continue to triangular numbers.
Save first — or use [a, b] = [b, a].
Exchange values safely — then use the idea in sorting.
save / set / restore
Classic[a, b] = [b, a]
JavaScriptints only
Trickstill correct
EdgeO(1)
AnalysisSwapping two values is a tiny step inside bigger ideas such as sorting (for example bubble sort compares and swaps neighbors). In JavaScript, [a, b] = [b, a] is the most readable everyday swap.
Learn how to check whether a number is triangular in JavaScript.
8 people found this page helpful