Swap Two Numbers in JavaScript
Temp variable, then destructuring. The second one is the one you keep.
BeginnerBasic ProgramsExample 5 of 10
swap-two-numbers.js
1// Method 1: Using a temporary variable2let a = 5;3let b = 10;4console.log("Before swap: a =", a, ", b =", b);56let temp = a;7a = b;8b = temp;9console.log("After swap: a =", a, ", b =", b);1011// Method 2: Using destructuring (ES6 - Modern approach)12let x = 5;13let y = 10;14console.log("Before swap: x =", x, ", y =", y);1516[x, y] = [y, x];17console.log("After swap: x =", x, ", y =", y);1819// Method 3: Using arithmetic (without temp variable)20let p = 5;21let q = 10;22console.log("Before swap: p =", p, ", q =", q);2324p = p + q;25q = p - q;26p = p - q;27console.log("After swap: p =", p, ", q =", q);
Output
Before swap: a = 5 , b = 10 After swap: a = 10 , b = 5 Before swap: x = 5 , y = 10 After swap: x = 10 , y = 5 Before swap: p = 5 , q = 10 After swap: p = 10 , q = 5
What's going on
Temp swap: three lines, easy to mess up.
[a, b] = [b, a] is the JS version. Right-hand side builds an array first. No temp.