How to use arithmetic operators In Javascript

In this approach, we start by taking the sum of two numbers. let’s take our numbers are ‘a’ and ‘b’. the sum of the two numbers is given to ‘a’.  b variable is updated with a value of ‘a-b’ and a is updated with ‘a-b’. 

Syntax: Initial values, a = 3, a = 5:

a = a + b // 8
b = a - b // 8-5=3
a = a - b // 8-3=5

Finally, the value of a will become 5, and the value of b will become 3.

Example:

Javascript
let a = 3, b = 5;

// Code to swap 'a' and 'b'
// a value changes to 8
a = a + b;

// b value changes to 3
b = a - b;

// a value changes to 5
a = a - b;

console.log(
    "After Swapping: x value is : "
    + a + " and b value is :" + b
);

Output
After Swapping: x value is : 5 and b value is :3

How to use arrays to swap variables in JavaScript ?

The technique of swapping two variables in coding refers to the exchange of the variables’ values. In an array, we can swap variables from two different locations. There are innumerable ways to swap elements in an array. let’s demonstrate a few ways of swapping elements such as:

Table of Content

  • Using a Temporary Variable
  • One-Line Swap
  • Using arithmetic operators
  • Using XOR Bitwise operator
  • Using Destructuring Assignment

Similar Reads

Using a Temporary Variable

We introduce a new variable and let it hold one of the two array values(a) which are willing to swap. The array value which we let the temporary variable hold is reassigned by the second array value(b). Finally, b(second variable) is given the value of temp which is a....

One-Line Swap

In the one-line swap, we take the array values we want to swap in a list according to indices and we directly assign the array values by changing the indices. Instead of doing it the hard way, there’s a very simple approach where we can swap variables directly, reassigning values at the same time....

Using arithmetic operators

In this approach, we start by taking the sum of two numbers. let’s take our numbers are ‘a’ and ‘b’. the sum of the two numbers is given to ‘a’.  b variable is updated with a value of ‘a-b’ and a is updated with ‘a-b’....

Using XOR Bitwise operator

In JavaScript, the bitwise XOR(^) Operator is used to compare two operands and return a new binary number which is 1 if both the bits in operators are different and 0 if both the bits in operads are the same. The operation is represented by the “|” symbol....

Using Destructuring Assignment

In JavaScript, swapping variables with destructuring assignment involves creating an array with the variables to be swapped, then using array destructuring to assign their values in reverse order, achieving a swift and concise exchange....