The blog provides the step by step solution to write a JavaScript program to swap two numbers. To understand the below given program , user should have knowledge on below given topics
Steps to be swap two numbers
The below given are the steps to write number swapping program in JavaScript
- Prompt user to enter the first number (X)
- Prompt user to enter the Second number (Y)
- Create a Temporary variable (Z) to store the value of first number (X)
- Assign first number (X) with the value of Second number (Y)
- Assign Second number (Y) with the value of Temporary variable Z
<script>
let X = prompt('Enter the first number: ');
let Y = prompt('Enter the second number: ');
let Z;
document.writeln(`Value for X ': ${X}` +"<br>");
document.writeln(`Value for Y ': ${Y}` +"<br>");
//swap variables
Z = X;
X = Y;
Y = Z;
document.writeln("Swap Values for X and Y " +"<br>");
document.writeln(`Value for X ': ${X}` +"<br>");
document.writeln(`Value for Y ': ${Y}` +"<br>");
</script>Output:
Value for X ': 5 Value for Y ': 7 Swap Values for X and Y Value for X ': 7 Value for Y ': 5