How to use Arithmetic Operators In Javascript

Example 1: The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.

Javascript
    // Javascript program to swap two
    // numbers without using temporary
    // variable

    let x = 10, y = 5;
    console.log("Before Swapping: x = " + 
        x + ", y = " + y);

    // Code to swap 'x' and 'y'

    // x now becomes 15
    x = x + y;

    // y becomes 10
    y = x - y;

    // x becomes 5
    x = x - y;

    console.log("After Swapping: x = " + 
        x + ", y = " + y);

Output
Before Swapping: x = 10, y = 5
After Swapping: x = 5, y = 10

Time Complexity: O(1)
Auxiliary Space: O(1)

Example 2: Multiplication and division can also be used for swapping.

Javascript
    // Javascript program to swap two numbers
    // without using a temporary variable
    let x = 10;
    let y = 5;

    console.log("Before swapping:" + " x = " + 
        x + ", y = " + y);

    // Code to swap 'x' and 'y'
    x = x * y; // x now becomes 50
    y = x / y; // y becomes 10
    x = x / y; // x becomes 5

    console.log("After swapping:" + " x = " + 
        x + ", y = " + y);

Output
Before swapping: x = 10, y = 5
After swapping: x = 5, y = 10

Time Complexity: O(1)
Auxiliary Space: O(1)

Javascript program to swap two numbers without using temporary variable

To swap two numbers without using a temporary variable, we have multiple approaches. In this article, we are going to learn how to swap two numbers without using a temporary variable.

Below are the approaches used to swap two numbers without using a temporary variable:

Table of Content

  • Using Arithmetic Operators
  • Using Bitwise XOR
  • A mixture of bitwise operators and arithmetic operators
  • One Line Expression

Similar Reads

Method 1: Using Arithmetic Operators

Example 1: The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum....

Method 2: Using Bitwise XOR

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. For example, XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111, and XOR of 7 (0111) and 5 (0101) is (0010)....

Method 3: A mixture of bitwise operators and arithmetic operators

The idea is the same as discussed in Method 1 but uses Bitwise addition and subtraction for swapping....

Method 4: One Line Expression

We can write only one line to swap two numbers....