Enter your keyword

post

Swap Two Variables

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

Code for swap two variables

//JavaScript program to swap two variables

//we will take input from the users
let a = prompt('Enter the first variable: ');
let b = prompt('Enter the second variable: ');

//create a temporary variable
let temp;

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

Leave a Reply

Your email address will not be published.