Swap Two Variables in Javascript

This is a preview lesson
Register or sign in to take this lesson.

With this example, we’ll learn how to swap two variables in javascript using temporary variable and destructuring syntax

In simple terms, swapping two numbers means reversing their values.

Using Temporary Variable

var name1 =  "Paul";
var name2 = "John";

console.log("Before swapping,  name1 value is " +name1);
console.log("Before swapping,  name2 value is " +name2);

var temporary_name = name1;
name1 = name2;
name2 = temporary_name;

console.log("After swapping,  name1 value is " +name1);
console.log("After swapping,  name2 value is " +name2);

In this example, we have defined two variables with values Paul and John first, then displayed the values before swapping them. Then, we have created a temporary variable, temporary_name, to hold the value of variable name1. We have assigned variable name2 to temporary_name, so that variable name2 can be updated with value of variable name1.


Therefore, now name1 is John and name2 is Paul. We can check the console to see the results of these variables before and after swapping.

Using the Destructuring Syntax

The destructuring syntax will allow us to extract the contents of the array, as well as the properties of the object, into distinct variables

var name1 =  "Paul";
var name2 = "John";

console.log("Before swapping,  name1 value is "  +name1);
console.log("Before swapping,  name2 value is "  +name2);

[name1,name2] = [name2,name1];
console.log("After swapping,  name1 value is "  +name1);
console.log("After swapping,  name2 value is "  +name2);

Here,We have used destructuring to swap the value of variable name1 and name2.

We unpack the values of array of [name2,name1 ]and store them in array of [name1,name2] using the destructuring assignment.

Conclusion

We have learned how to swap two variables in javascript using temporary variables and destroying syntax in this article.