5

JavaScript Program to Swap Two Numbers

 2 years ago
source link: https://www.geeksforgeeks.org/videos/javascript-program-to-swap-two-numbers/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript Program to Swap Two Numbers

JavaScript Program to Swap Two Numbers
Hey everyone, welcome to be super Geeks. So, in this
  • 60 Views
  • 23/08/2022

In this video, we will write a JavaScript Program to Swap two Numbers. So basically, the exchange of two numbers in the JavaScript programming language can be defined as the exchange of the values of two variables.

Take an example, if we have two variables num1 & num2. The value of num1 is 21 & value of num2 is 16. So after swapping the value of num1 will become 16 and the value of num2 will become 21.

Algorithm for Swapping 2 numbers in Java Script:
Step 1: Consider two variables with valid values.
Step 2: Store the value of the first variable in a temporary variable.
Step 3: Store the value of the second variable in the first variable.
Step 4: Now store the value of the temporary variable in the second variable.
Step 5: Print the first and second variables.

Here we see four different methods to Swap two Numbers in JavaScript:

  1. Using Temporary variable
  2. Using destructuring assignment
  3. Using Arithmetic Operators
  4. Using XOR operator

In the first method, we take a temp variable to swap values. 

In the second method, we use the destructuring assignment of JavaScript. It is a JavaScript expression that allows unpacking values. 

By using an arithmetic operator we get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum. 

The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ.

How to swap two numbers without using a temporary variable?
https://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK