js swap two numbers

bibhupadhy

Bibhu Padhy

Posted on February 21, 2021

js swap two numbers

Swap two numbers, a common problem-solving interview question.

  1. Using a Variable

function swapTwoNumbers(a, b) {
let temp = a;
a = b;
b = temp
return [a, b];
}

console.log(swapTwoNumbers(10, 5))
// output a = 5, b = 10


  1. Using arithmetic operators

function swapTwoNumbers(a, b) {
a = a + b; // 15
b = a - b; // 15 - 5 = 10
a = a - b; // 15 - 10 = 5
return [a, b];
}

console.log(swapTwoNumbers(10, 5))

// output a = 5, b = 10


  1. Using Destructuring

function swapTwoNumbers(a, b) {
return [a, b] = [b, a]
}

console.log(swapTwoNumbers(10, 5))

💖 💪 🙅 🚩
bibhupadhy
Bibhu Padhy

Posted on February 21, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related