JavaScript Swap Two Numbers Program

Beginner
5 min read
Updated: Oct 2026
3 programs
Live preview

What Does Swap Two Numbers Mean?

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]
MethodIdeaNotes
Temp variableSave, overwrite, restoreClearest interview answer
Destructuring[a, b] = [b, a]Idiomatic modern JavaScript
XORThree ^= stepsIntegers only; interview trick

How to Swap Two Numbers in JavaScript

Four clear steps for the temp method — then modern and no-temp variants.

  1. Store the first value in temp.
  2. Copy the second value into the first variable.
  3. Copy temp into the second variable.
  4. Or show destructuring / XOR as alternatives when asked.
MethodIdeaTimeBest for
Temp variabletemp = a; a = b; b = temp;O(1)Interviews, any language
Destructuring[a, b] = [b, a]O(1)Everyday JavaScript
XORa ^= b three timesO(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

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
DefaultUse a temporary variable
Temp stepstemp = a; a = b; b = temp;
Modern JS[a, b] = [b, a]
Equal valuesSwap still works; result unchanged
XORIntegers only; optional trick
Classic check5, 10 → 10, 5

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

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.

JavaScript
let num1 = 5;
let num2 = 10;

console.log("Before swapping: num1 = " + num1 + ", num2 = " + num2);

let temp = num1;
num1 = num2;
num2 = temp;

console.log("After swapping: num1 = " + num1 + ", num2 = " + num2);
Try It Yourself

How It Works

  1. temp = num1 saves 5 so it is not lost.
  2. num1 = num2 copies 10 into the first variable.
  3. num2 = temp restores the saved 5.
  4. Works for equals, negatives, and any assignable type.
  5. This is the answer to give first in interviews.

Example 2 — Swap Using Destructuring

One line: build a temporary array on the right, then unpack into both variables.

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

How It Works

  1. The right side builds [10, 5] from the current values.
  2. The left side unpacks that array into num1 and num2.
  3. No named temp — the array is a short-lived temporary.
  4. Works for strings, objects, and any assignable values — not just numbers.
  5. 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);
Try It Yourself

How It Works

  1. a ^= b mixes both bit patterns into a.
  2. b ^= a recovers the original a into b.
  3. a ^= b recovers the original b into a.
  4. The a !== b guard is a safe habit for equal values.
  5. Prefer temp or destructuring for readability; mention XOR only if asked.

Edge Cases & Pitfalls

Check these before calling the solution done.

Equal

Same values

Swap still runs; both variables keep the same number.

Const

Need reassignment

Use let (not const) — swap reassigns both variables.

XOR

Integers only

Bitwise XOR is not for floats or general objects. Temp and destructuring work more broadly.

Readability

Temp first in interviews

Lead with temp. Use destructuring in real JS; treat XOR as optional.

Time and Space Complexity

ProgramTimeExtra space
Temp variableO(1)O(1)
DestructuringO(1)O(1)
XORO(1)O(1)

A swap touches a fixed number of variables — constant time and space.

Key Takeaways

  • Goal: exchange the values stored in two variables.
  • Interview default: temp = a; a = b; b = temp;
  • Modern JS: [a, b] = [b, a]
  • Test set: (5,10) → (10,5); (4,4) stays; negatives work with temp.

One line: save one value, overwrite it, then put the saved value into the other variable.

Frequently Asked Questions

After a swap, the first variable holds the old second value, and the second holds the old first value.
Not always. Destructuring or XOR can swap without a named temp, but a temporary variable is the clearest default in interviews.
[a, b] = [b, a] using array destructuring — short, readable, and works for any values.
Swap still works; both values remain the same.
Yes. Temp and destructuring work for any values. XOR also works for integers.
All common swap methods are O(1) time and O(1) extra space.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the values and Run.

Next: Triangular Number

Check whether a number sits in the sequence 1, 3, 6, 10, …

Triangular number tutorial →

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.

10 people found this page helpful