JavaScript: Swap Two Variables

1. Introduction

Swapping two variables means interchanging their values. If variable a holds the value 5 and variable b holds the value 10, then after swapping, variable a will hold the value 10 and variable b will hold the value 5. In this tutorial, we will explore different methods to achieve this using JavaScript.

2. Program Overview

We will demonstrate three methods to swap two variables:

1. Using a temporary variable.

2. Using array destructuring.

3. Using arithmetic operations.

3. Code Program

// Method 1: Using a temporary variable
let a = 5, b = 10;
let temp;
temp = a;  // Save the value of 'a' into 'temp'
a = b;     // Assign the value of 'b' to 'a'
b = temp;  // Assign the saved value of 'a' (which is in 'temp') to 'b'
console.log(After swapping (Method 1): a = ${a}, b = ${b});

// Resetting values for next demonstration
a = 5; b = 10;

// Method 2: Using array destructuring
[a, b] = [b, a];
console.log(After swapping (Method 2): a = ${a}, b = ${b});

// Resetting values for next demonstration
a = 5; b = 10;

// Method 3: Using arithmetic operations (works for numbers only)
a = a + b;
b = a - b;
a = a - b;
console.log(After swapping (Method 3): a = ${a}, b = ${b});


After swapping (Method 1): a = 10, b = 5
After swapping (Method 2): a = 10, b = 5
After swapping (Method 3): a = 10, b = 5

4. Step By Step Explanation

1. Using a Temporary Variable:

- We introduce a third variable called temp.

- We store the value of a in temp.

- Then, we assign the value of b to a.

- Finally, we assign the saved value from temp to b.

2. Using Array Destructuring:

- This method takes advantage of JavaScript's array destructuring feature.

- We are essentially creating an array [b, a] and then destructuring it to [a, b], which swaps their values.

3. Using Arithmetic Operations:

- This method works only for numbers.

- We utilize arithmetic operations to swap the values without needing a third variable.

- First, we add the two variables and store the result in a.

- To get the original value of a, we subtract b from the new a and assign the result to b.

- Then, to get the original value of b, we subtract the new b from a and assign the result back to a.Each of these methods has its own use cases and considerations. 

The method using array destructuring is concise and often preferred in modern JavaScript development, while the method using arithmetic operations is more of a novelty and can be useful in situations where memory is extremely constrained.