JavaScript program to swap two variables using a temporary variable

Configurare noua (How To)

Situatie

We created a temp variable to store the value of a temporarily.
We assigned the value of b to a.
The value of temp is assigned to b
As a result, the value of the variables are swapped.

Solutie

Pasi de urmat

//JavaScript program to swap two variables

//take input from the users
let a = prompt(‘Enter the value of a: ‘);
let b = prompt(‘Enter the value of b: ‘);

//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

Enter the first variable: 4
Enter the second variable: 2
The value of a after swapping: 2
The value of b after swapping: 4

Tip solutie

Permanent

Voteaza

(9 din 18 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?