Write a JavaScript program to swap two variables

Description: Swap the values of two variables a and b.

Hint:

  • The old way uses a third variable.
  • The modern way uses array destructuring.

JavaScript program to swap two variables

let a = 10;
let b = 20;
console.log("Before:", a, b);

[a, b] = [b, a];

console.log("After:", a, b);

Output:

Tutorials Class - Output Window

Before: 10 20
After: 20 10

How it works

  • The right side [b, a] makes a new array with the two values.
  • The left side [a, b] destructures it back into the variables, so they are swapped in one line.

Read ES6 Features.


Learn more about the similar topics:
Tutorials
JavaScript Variables
JavaScript Scope
JavaScript Data Types
JavaScript Type Conversion
JavaScript Operators
JavaScript Numbers and Math
Exercises & Assignments
Write a JavaScript program to add two numbers
Write a JavaScript program to swap two variables
Interview Questions & Answers
What are the data types in JavaScript?
What is the difference between == and === in JavaScript?
What is NaN in JavaScript?
What is the difference between null and undefined?
What is scope in JavaScript?
What is the difference between var, let and const?
What is hoisting in JavaScript?