- num1
- 5
- num2
- 10
Swap Two Numbers in JavaScript
What you’ll learn
- What swapping means in everyday terms (two values trade places).
- The classic three-step pattern with a
tempvariable—and why you need it. - A version with a function helper that returns swapped values, plus a version that stays entirely inline.
- A destructuring pattern that swaps without any
tempvariable (very common in JavaScript). - A live preview, short notes on arithmetic swaps, and interview-style pitfalls.
Overview
You have two labeled boxes, num1 and num2. Swapping means: whatever was inside the first box moves to the second, and whatever was in the second moves to the first. A third spare box, temp, holds one value for a moment so nothing gets erased too early.
Three code examples
Example 1: function helper and temp. Example 2: same idea inline. Example 3: destructuring swap with no extra variable.
Live preview
Type two integers and press Swap to see “before” and “after” lines that match the C idea.
Extras you may hear in class
After Example 3, the notes recap why add/subtract swaps can overflow and why temp stays the default in real code.
Prerequisites
You should know what variables are and how to print with console.log().
- Basic JavaScript syntax, assignment
a = b, and functions. - Optional: familiarity with array destructuring like
[a, b] = [b, a].
What does swapping do?
After a correct swap, the first variable shows the value the second used to have, and the second shows what the first used to have. Order matters in sorting; swapping is the smallest “exchange” step.
Picture two full cups. You cannot pour both into each other at once without spilling. So you use a third empty cup (temp) to hold one drink while you move the other.
Why return values from a helper?
In JavaScript, function parameters are local bindings. A clear pattern is to return swapped values from the helper and assign them back: [a, b] = swapNumbers(a, b). This keeps behavior explicit and easy to test.
function swapNumbers(a, b) { return [b, a]; } and then [num1, num2] = swapNumbers(num1, num2).
Trace on paper
- Why
- Save the old
num1before overwriting it.
- num1
- 10
- num2
- 5
Live preview
Uses the same three-step pattern in JavaScript. Values stay inside safe integers.
Algorithm
Goal: exchange the values in two integer variables using a temporary third integer.
Copy first into temp
temp = a;
Move second into first
a = b;
Move saved value into second
b = temp; (or *b = temp;).
📜 Pseudocode
procedure swap(a, b): // a and b name two storage slots
temp ← a
a ← b
b ← tempFunction helper (classic interview style)
swapNumbers returns both values in swapped order. This keeps the logic reusable and clear.
function swapNumbers(a, b) {
const temp = a;
a = b;
b = temp;
return [a, b];
}
let num1 = 5;
let num2 = 10;
console.log("Before swapping: num1 = " + num1 + ", num2 = " + num2);
[num1, num2] = swapNumbers(num1, num2);
console.log("After swapping: num1 = " + num1 + ", num2 = " + num2);Explanation
const temp = a;Save the first value. This temporary slot prevents the first value from being overwritten too early.
a = b; b = temp;Finish the exchange. Then return both values so the caller can assign them back.
Inline swap with temp
Same three moves directly where values are used. This is often the easiest beginner version.
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);Explanation
Because JavaScript variables are directly reassigned here, plain assignments are enough.
Without any temp variable (destructuring)
Array destructuring swaps values in one line without a third variable. This is the most common JavaScript no-temp style.
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);Explanation
Destructuring builds a two-item array on the right and assigns values back in swapped order on the left. It is concise and readable in JavaScript.
[num1, num2] = [num2, num1];One-line exchange. Both old values are read first, then written back in opposite positions.
const temp = num1; num1 = num2; num2 = temp;Equivalent logic. Destructuring is just a cleaner JavaScript syntax for the same swap idea.
Other swap styles
Destructuring swap. Shown in Example 3. It is concise and common in JavaScript.
Add/subtract swap. Ideas such as a = a + b; b = a - b; a = a - b; may lose precision in JavaScript for large values. Prefer temp for clarity.
Interview: show temp swap first, then mention destructuring as a JavaScript idiom.
❓ FAQ
🔄 Input / output examples
Each sample prints two lines (before and after). Replace literals directly or parse input using prompt, form fields, or Node.js stdin.
| num1, num2 (before) | After swap |
|---|---|
| 5, 10 | 10, 5 |
| 0, 3 | 3, 0 |
| -4, 20 | 20, -4 |
| 7, 7 | 7, 7 |
Edge cases
Most mistakes come from assignment order or from overly clever swap tricks.
swapNumbers(a, b) without using its return value
If a helper returns swapped values, you must assign them back. Example: [a, b] = swapNumbers(a, b).
Never start with a = b alone
You lose the original a and cannot recover it for b without a saved copy.
Arithmetic swaps
Adding very large numbers can exceed safe integer precision in JavaScript. Stick to temp or destructuring.
Destructuring readability
Destructuring is concise, but beginners should still understand the temp-based three-step logic underneath.
⏱️ Time and space complexity
| Version | Time | Extra space |
|---|---|---|
| Temp swap (Examples 1 & 2) | O(1) | O(1) (one integer) |
| Destructuring swap (Example 3) | O(1) | O(1) (no explicit temp variable) |
| Add/subtract trick | O(1) | O(1); watch overflow |
Summary
- Pattern:
temp = a; a = b; b = temp;is the core swap logic. - Functions: return swapped values and assign them back in the caller.
- Extras: Example 3 shows destructuring without
temp; temp stays the readable default.
Swapping two values is a tiny step inside bigger ideas such as sorting (for example bubble sort compares and swaps neighbors). The three-line pattern with a temp variable is the clearest way to explain what “exchange” means to a computer.
8 people found this page helpful
