Home / javascript / How to swap two numbers without using a temporary variable?
Swap Two Numbers
Swap Two Numbers

How to swap two numbers without using a temporary variable?

Solution – 1 – Using Arithmetic Operators

function swapNumb(a, b){
  console.log('Before swap Output: ','a: ', a, 'b: ', b);
  b = b -a;
  a = a+ b;
  b = a-b;
  console.log('After swap Output: ','a: ', a, 'b: ', b);  
}

swapNumb(2, 3);

Solution – 2 – Using Bitwise XOR

function swapNumb(a, b){
  console.log('Before swap Output: ','a: ', a, 'b: ', b);
  a = a ^ b;
  b = a ^ b;
  a = a ^ b;
  console.log('After swap Output: ','a: ', a, 'b: ', b);  
}
swapNumb(2, 3);

About Sushil Kumar

Check Also

What is hoisting in javascript with example?

Hoisting in JavaScript is a behavior where variable and function declarations are moved to the …

Leave a Reply

Your email address will not be published. Required fields are marked *