Skip to content

JavaScript Swap Two Variables Example

Ramesh Fadatare edited this page Aug 11, 2020 · 1 revision

In this example, you will learn to write a program to swap two variables in JavaScript using various methods.

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
Clone this wiki locally