Javascript Everywhere

Help for javascript developer

Javascript Everywhere in the world

Monday, April 27, 2020

JavaScript Challenges: How to swap two variable without using third one?

Without third variable swap to variable
Swap to variable in javascript without using the third variable

Introduction:
    Many javascript developers ask a question, How many ways to swap two variables without using third. Our answer is there are many ways we can achieve this but we always go with the easiest and fast solution. Every language provides a different way of doing the swap variables.

Challenge:

Challenge is declared two variable and swap value between without using the third variable like

Input: var a = 10;
           var b = 20;
          console.log(a, b) is give output like (10, 20)
Output: console.log(a, b) is output like (20, 10)

The logic of this program is many, we provide the best solution here:
The program output is:
1)

var a = 10;
var b = 20;
[a, b] = [b, a];
console.log(a, b);
2)
let a = 10;
let b = 20;
a = a * b;
b = a / b;
a = a / b;
console.log(a, b)
3)

var a = 10;
var b = 20;
console.log(a,b);
a = new Array(a,b);
b = a[0];
a = a[1];
console.log(a,b);

Explanation: There are many ways you can perform this program. You are free to ask question and comment, I will reply and give you a proper solution.


Other: Reverse string without using the built-in function