How to Swap Two Variables Without Using Third Variable in Javascript

In this tutorial, you will learn how to swap two variables without using third variable in javascript. I know the question here does sound a bit tricky and interesting.  As a newbie, it can be a bit challenging to determine how to get this done, but in any programming language to become a good developer, you have to be smart.

Swapping values of 2 variables can be easily achieved using array destructuring.  If you know how array destructuring works, then you can swap values of as many variables as you want without creating any extra variables.

In the following example, we have 2 variables and upon click of a button, we will swap their values, form a template string, and display that on the screen. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The button element has “Get” and the h1 element has “Result” as innerText.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button>Get</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button{
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected the button element and h1 element using the document.querySelector() method and stored them in btnGet and result variables respectively.
  • We have 2 global variables a and b.
  • We have attached a click event listener to the button element.
  • On the right-hand side, we have [a,b]. This means we have created a completely new array that has only 2 elements a and b and now we are going to destructure it.
  • On the left-hand side, we have [b,a] and notice that the variables are now in reverse order. Due to array destructuring, the value of a on the right-hand side will be assigned to variable b and the value of b on the right-hand side will be assigned to a.
  • After destructuring, we are simply creating a template string and displaying that in the h1 element using the innerText property.
let btnGet = document.querySelector('button');
let result = document.querySelector('h1');

let a = 'James';
let b = 'Marks';

btnGet.addEventListener('click', () =>{
    [b, a] = [a,b];
    result.innerText = `a: ${a} - b: ${b}`;
});