JavaScript Swap Two Numbers

You are Here:

JavaScript Program to Swap Two Numbers

In programming, there are two different techniques to swap any two numbers in a variable, they are

  • Swap using Temporary Variable
  • Swap without using Temporary Variable

Swap using Temporary Variable

In the following example, we will swap two numbers (25 and 50) using a temporary variable (temp).

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h1>JS Swap Two Numbers</h1> <script> var num1 = 25; var num2 = 50; var temp = 0; document.write("<br>Before Swap, num1 = " +num1+" num2 = "+num2); temp = num1; num1 = num2; num2 = temp; document.write("<br>After Swap, num1 = " +num1+" num2 = "+num2); </script> </body> </html>

Swap without using Temporary Variable

In the following example, we will swap two numbers (25 and 50) without using a temporary variable.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h1>JS Swap Two Numbers</h1> <script> var num1 = 25; var num2 = 50; document.write("<br>Before Swap, num1 = " +num1+" num2 = "+num2); num1 = num1 - num2; num2 = num1 + num2; num1 = num2 - num1; document.write("<br>After Swap, num1 = " +num1+" num2 = "+num2); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author