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
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The
button
element has“Get”
and theh1
element has“Result”
asinnerText
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
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 andh1
element using thedocument.querySelector()
method and stored them inbtnGet
andresult
variables respectively. - We have 2 global variables
a
andb
. - We have attached a
click
event listener to thebutton
element. - On the right-hand side, we have
[a,b]
. This means we have created a completely new array that has only 2 elementsa
andb
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 ofa
on the right-hand side will be assigned to variableb
and the value ofb
on the right-hand side will be assigned toa
. - After destructuring, we are simply creating a template string and displaying that in the
h1
element using theinnerText
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}`; });