Swap Two Numbers
Program to swap values of two variables
JavaScript Swap Two Numbers Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Using a temporary variable
let a = 5;
let b = 10;
console.log("Before swap: a =", a, ", b =", b);
let temp = a;
a = b;
b = temp;
console.log("After swap: a =", a, ", b =", b);
// Method 2: Using destructuring (ES6 - Modern approach)
let x = 5;
let y = 10;
console.log("Before swap: x =", x, ", y =", y);
[x, y] = [y, x];
console.log("After swap: x =", x, ", y =", y);
// Method 3: Using arithmetic (without temp variable)
let p = 5;
let q = 10;
console.log("Before swap: p =", p, ", q =", q);
p = p + q;
q = p - q;
p = p - q;
console.log("After swap: p =", p, ", q =", q);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
Understanding Swap Two Numbers
This program demonstrates different methods to swap two variable values in JavaScript.
Method 1: Temporary Variable
The most straightforward and readable approach:
Pros:
Cons:
Method 2: Destructuring Assignment (ES6)
Modern JavaScript feature that's clean and elegant:
[a, b] = [b, a];
How it works:
Pros:
Cons:
Method 3: Arithmetic Swap
Uses addition and subtraction (only works with numbers):
a = a + b;
b = a - b;
a = a - b;
Pros:
Cons:
When to Use:
-
Method 1:
General purpose, most readable
-
Method 2:
Modern code, any data type
-
Method 3:
Only for numbers, when memory is critical
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.