Swap two numbers, a common problem-solving interview question.
- 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
- 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
- Using Destructuring
function swapTwoNumbers(a, b) {
return [a, b] = [b, a]
}
console.log(swapTwoNumbers(10, 5))
Top comments (0)