Swap Two Numbers

Program to swap values of two variables

JavaScriptBeginner
JavaScript
// Method 1: Using a temporary variable
let a = 5;
let b = 10;
console.log("Before swap: a =", a, ", b =", b);

let temp = a;
a = b;
b = temp;
console.log("After swap: a =", a, ", b =", b);

// Method 2: Using destructuring (ES6 - Modern approach)
let x = 5;
let y = 10;
console.log("Before swap: x =", x, ", y =", y);

[x, y] = [y, x];
console.log("After swap: x =", x, ", y =", y);

// Method 3: Using arithmetic (without temp variable)
let p = 5;
let q = 10;
console.log("Before swap: p =", p, ", q =", q);

p = p + q;
q = p - q;
p = p - q;
console.log("After swap: p =", p, ", q =", q);

Output

Before swap: a = 5 , b = 10
After swap: a = 10 , b = 5
Before swap: x = 5 , y = 10
After swap: x = 10 , y = 5
Before swap: p = 5 , q = 10
After swap: p = 10 , q = 5

This program demonstrates different methods to swap two variable values in JavaScript.

Method 1: Temporary Variable

The most straightforward and readable approach:

  1. Store first value in temporary variable
  2. Assign second value to first variable
  3. Assign temporary value to second variable

Pros:

  • Easy to understand
  • Works with any data type
  • Most readable

Cons:

  • Requires extra memory for temp variable

Method 2: Destructuring Assignment (ES6)

Modern JavaScript feature that's clean and elegant:

javascript
[a, b] = [b, a];

How it works:

  • Creates an array with swapped values
  • Destructures into variables
  • All in one line!

Pros:

  • Concise and modern
  • No temporary variable needed
  • Works with any data type
  • Most elegant solution

Cons:

  • Requires ES6 support
  • Slightly less intuitive for beginners

Method 3: Arithmetic Swap

Uses addition and subtraction (only works with numbers):

javascript
a = a + b;
b = a - b;
a = a - b;

Pros:

  • No temporary variable
  • Works with numbers

Cons:

  • Only works with numbers
  • Risk of overflow with large numbers
  • Less readable

When to Use:

  • Method 1: General purpose, most readable

  • Method 2: Modern code, any data type

  • Method 3: Only for numbers, when memory is critical