JavaScript Program to Swap Two Variables

Write a JavaScript program to swap two variables in JavaScript using various methods.
Check out all 100 + JavaScript Examples
Check out all JavaScript programs at All JavaScript Programs 

Example 1: Using a Temporary Variable

let a = 10;
let b = 20;

//create a temporary variable
let temp;

//swap variables
temp = a;
a = b;
b = temp;

console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);

Output

The value of a after swapping: 20
The value of b after swapping: 10

Example 2: Using Arithmetic Operators

let a = 10;
let b = 20;

// addition and subtraction operator
a = a + b;
b = a - b;
a = a - b;

console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);

Output

The value of a after swapping: 20
The value of b after swapping: 10


Comments