javascript Swapping Variables
- Published
- Reading time
- 1 min read
- Length
- 163 words
On this page
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: 5Method 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: 5Method 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: 5These are the three methods to swap two variables in Javascript.