js swap two numbers
Bibhu Padhy
Posted on February 21, 2021
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))
💖 💪 🙅 🚩
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
reactnative I have an error when installing and using the react-native-bluetooth-serial-next library on an ios device.
November 29, 2024
programming Supercharge Your Node.js: WebAssembly's Game-Changing Performance Boost
November 28, 2024