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 admin

Check Also

What are the differences between var, let and const in JavaScript?

var, let, and const are all used for variable declaration in JavaScript, but they have …

Leave a Reply

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