JavaScript Program to Swap Two Variables

In this post, we will learn how to swap two variables using JavaScript Programming language.

This program asks the user to enter two numbers, then it swaps those two numbers using a temporary variable.

So, without further ado, let’s begin this tutorial.

JavaScript Program to Swap Two Variables

// JavaScript Program to Swap Two Variables

// Asking for input
var num1 = prompt("Enter first number: ");
var num2 = prompt("Enter second number: ");

// Temporary variable
var temp;

// Swapping two variables
temp = num1;
num1 = num2;
num2 = temp;

// Displaying output
console.log("The value of first number after swapping: " + num1);
console.log("The value of second number after swapping: " + num2);

Output

The value of first number after swapping: 7
The value of second number after swapping: 5

How Does This Program Work ?

// Asking for input
var num1 = prompt("Enter first number: ");
var num2 = prompt("Enter second number: ");

In this program, the user is asked to enter two numbers. These numbers get stored in the num1 and num2 named variables.

// Temporary variable
var temp;

We create a temporary variable named temp.

// Swapping two variables
temp = num1;
num1 = num2;
num2 = temp;

We swap these two numbers with the help of a temporary variable.

// Displaying output
console.log("The value of first number after swapping: " + num1);
console.log("The value of second number after swapping: " + num2);

Finally, the swapped numbers are displayed on the screen using the console.log function.

Conclusion

I hope after going through this post, you understand how to swap two variables using JavaScript Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *