JavaScript Code


Swap Two Variables – JavaScript Program


Swap Two Variables Program

In this tutorial, you write a JavaScript program to swap the values in two variables.

Solution

To swap the values in a two variables, we can use a temporary variable, or destructuring assignment. We can also use arithmetic operators if the values are numbers.

Programs

1. In the following program, we swap values in two variables using temporary variable.

var a = 5;
var b = 7;

var temp;
temp = a;
a = b;
b = temp;

console.log('a : '+a);
console.log('b : '+b);

2. In the following program, we swap numeric values in two variables using Arithmetic Operators.

var a = 5;
var b = 7;

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

console.log('a : '+a);
console.log('b : '+b);

3. In the following program, we swap two variables using destructuring assignment.

var a = 5;
var b = 7;

[a, b] = [b, a]

console.log('a : '+a);
console.log('b : '+b);