Swap two numbers without using third variable in JavaScript

Swapping two numbers are very easy, but its very trendy among new language learner. And it should trendy because its little tricky and mathematical. These is a very basic program and I am pretty assure if you have started learning programming language using any language you have done this. But, in case if you have just started learning programming then you will learn today. Lets discuss whats are the problem statements on today blog.

  1. How to swap two numbers without third variable
  2. We will use ES6 class based structure to swap numbers
  3. How to create object in JavaScript using new.

Class based Swapping program in JavaScript

I have took class based approach here because we should write modular code because It helps us to make code readable and also reusable.

/**
*
* Swapping two numbers without third variable
*
*/
class SwapNum{
     
	constructor(a, b){
		this.a = a;
		this.b = b;
	}

        // Swap method
	swapNumber()
	{
		try{

			this.b = this.a + this.b;
			this.a = this.b - this.a;
			this.b = this.b - this.a;
			return "Value of a is: "+ this.a+ " and the Value of b is: "+ this.b;
		
		}catch(e){

			console.log(e);
		}
	}
}

// Create object of the class
let obj1 = new SwapNum(5, 7);
let obj2 = new SwapNum(1001, 1213);
let obj3 = new SwapNum(4345, 2334);
let obj4 = new SwapNum(12434, 3343);

// It will print on console with each newline 
console.log(obj1.swapNumber());
console.log(obj2.swapNumber());
console.log(obj3.swapNumber());
console.log(obj4.swapNumber());

Outputs :

Value of a is: 7 and the Value of b is: 5
Value of a is: 1213 and the Value of b is: 1001
Value of a is: 2334 and the Value of b is: 4345
Value of a is: 3343 and the Value of b is: 12434

Conclusion: Some time we ignore this program but swapping two number without third variable is always trending among the fresher interview. trending I know this is a very basic programming topic but its also true that it is good to start.

Leave a Reply

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