DEV Community

Bibhu Padhy
Bibhu Padhy

Posted on

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))

Top comments (0)