Swap Two Numbers in JavaScript

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 3 Code Examples
Variables

What you’ll learn

  • What swapping means in everyday terms (two values trade places).
  • The classic three-step pattern with a temp variable—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 temp variable (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.

JavaScript pattern

function swapNumbers(a, b) { return [b, a]; } and then [num1, num2] = swapNumbers(num1, num2).

Trace on paper

Start Before
num1
5
num2
10
temp Holds 5
Why
Save the old num1 before overwriting it.
Done After
num1
10
num2
5

Live preview

Uses the same three-step pattern in JavaScript. Values stay inside safe integers.

Enter integers (try negatives too). Press Swap or Enter in either field.

Live result
Press “Swap” to see before and after values.

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

Pseudocode
procedure swap(a, b):  // a and b name two storage slots
    temp ← a
    a ← b
    b ← temp
1

Function helper (classic interview style)

swapNumbers returns both values in swapped order. This keeps the logic reusable and clear.

JavaScript
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);
Try it Yourself

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.

2

Inline swap with temp

Same three moves directly where values are used. This is often the easiest beginner version.

JavaScript
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);
Try it Yourself

Explanation

Because JavaScript variables are directly reassigned here, plain assignments are enough.

3

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.

JavaScript
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);
Try it Yourself

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

After swapping, the first variable holds what the second used to hold, and the second holds what the first used to hold. If you start with 5 and 10, you end with 10 and 5.
If you write a = b first, you lose the old value of a before you can copy it into b. A spare box called temp remembers the first value while you move things around.
Function parameters are local bindings in JavaScript. Returning both values (for example as an array) makes the swap explicit and easy to assign back.
Yes. Example 3 on this page uses JavaScript destructuring. Add/subtract patterns also exist but are less readable and can lose precision for very large values.
Each swap is a few assignments: constant time O(1) and constant extra space.
Swapping 7 and 7 still works; nothing visible changes. Both temp swap and destructuring handle this cleanly.

🔄 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, 1010, 5
0, 33, 0
-4, 2020, -4
7, 77, 7

Edge cases

Most mistakes come from assignment order or from overly clever swap tricks.

Copies

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).

Order

Never start with a = b alone

You lose the original a and cannot recover it for b without a saved copy.

Overflow

Arithmetic swaps

Adding very large numbers can exceed safe integer precision in JavaScript. Stick to temp or destructuring.

Style

Destructuring readability

Destructuring is concise, but beginners should still understand the temp-based three-step logic underneath.

⏱️ Time and space complexity

VersionTimeExtra 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 trickO(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.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful