javascript Swapping Variables

Javascript Swapping Variables

Swapping variables is a common operation in programming. In Javascript, we can swap two variables using multiple methods.

Method 1: Using a temporary variable

We can swap two variables using a temporary variable which will hold the value of one variable temporarily:


let x = 5;
let y = 10;

let temp = x;
x = y;
y = temp;

console.log("x:", x); // Output: x: 10
console.log("y:", y); // Output: y: 5

Method 2: Using arithmetic operations

We can also swap two variables using arithmetic operations:


let x = 5;
let y = 10;

x = x + y;
y = x - y;
x = x - y;

console.log("x:", x); // Output: x: 10
console.log("y:", y); // Output: y: 5

Method 3: Using destructuring assignment

We can swap two variables using destructuring assignment:


let x = 5;
let y = 10;

[x, y] = [y, x];

console.log("x:", x); // Output: x: 10
console.log("y:", y); // Output: y: 5

These are the three methods to swap two variables in Javascript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe