By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > How to Swap Two Numbers Without A Third Variable in JS
JavaScriptprogramming

How to Swap Two Numbers Without A Third Variable in JS

Admin
Last updated: 2022/12/12 at 5:28 AM
Admin
Share
8 Min Read
Swap Two Numbers Without A Third Variable

In this article, we will learn to make a program to swap two numbers without a third variable in JavaScript. As a JavaScript beginner, you might have done this program using third variable. But have you ever think, “is there any way to do this same thing without a third variable?”. So yes we can do it in many ways, and it has its own benefit like we can save memory and partially some performance using this method.

Contents
Mathematical OperationXOR OperatorSingle Line SwappingDestructuring Array Method (1)Bonus MethodYou may also like:

So let’s begin coding and make it step-by-step. And if you are not a beginner then also you will learn some new things.

There are 4 different methods to make this program:

  • Mathematical Operation
  • XOR Operator
  • Single Line Swapping
  • Destructuring Assignment Array

Mathematical Operation

Okay, we will make this program with the help of basic operation, where we will use addition and subtract operators.

In this method, we have a = 10 and b =2 initially, here we added both value and assigned to a, So a = 12. Then we have subtracted the value of b from a and assigned to b, so it will be 12-2 =10 which is b’s value. Then we have subtracted b’s value, which is 10 from a, so 12-10 =2 which is now a’s value.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var a = 10;
        var b = 2;
        document.write("First Method </br>")
        a = a+b; //a= 10+2 = 12
        b = a-b; //b= 12-2 = 10
        a = a-b; //a= 12-10 = 2
        document.writeln("value of a = "+a+"</br>");
        document.writeln("value of b = "+b+"</br>");
   </script>
    
</body>
</html>
Swap Two Numbers Without A Third Variable

XOR Operator

Now let’s move on to the second method, here we will use XOR(Exclusive-OR) Operation to get the result. We have again assigned the same values to a and b, then we used a^b which means (a XOR b). So as we know XOR Operations when two binary digits are same then the resultant digit will be 0, otherwise 1.

So what we do here is we are converting the a and b values to binary and matching both digits to get the result. Here (a^b= 1010 ^ 0010 = 1000), as we know, 1010 is binary of 10 and 0010 is binary of 2 and 1000 is binary of 8, so we got a =8. Then we have again did same operation (a^b) assigned to b, so b = 10. Then again we have did same operation (a^b) and assigned to a, so a =2.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var a = 10;
        var b = 2;
        document.write("Second Method </br>")
        a = a^b; //a= 1010 ^ 0010 = 1000 = 8
        b = a^b; //b= 1000 ^ 0010 = 1010 = 10
        a = a^b; //a= 1000 ^ 1010 = 0010 = 2
        document.writeln("value of a = "+a+"</br>");
        document.writeln("value of b = "+b+"</br>");
    </script>
    
</body>
</html>
Swap Two Numbers Without A Third Variable

Single Line Swapping

Now we will make this same program in one line of operation. Here we again assigned the same values to a and b. Now we have used a = b + (b=a, 0), Here b will be 2 and (b=a) will run, so b=10, also (b=a, 0) will return 0, so (b=a, 0) will be 0. Ultimately, a= b + 0, resultant a = 2 and since we run (b=a, 0) so b’s value will be updated to 10.

Note: In parentheses part, we have did some operation at first and returned some value using comma operator.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var a = 10;
        var b = 2;
        document.write("Third Method </br>")
        a = b + (b=a, 0); //here a = b + 0 because a will be assigned to b and (b=a, 0) wil return 0
        document.writeln("value of a = "+a+"</br>");
        document.writeln("value of b = "+b+"</br>");
    </script>
    
</body>
</html>
Swap Two Numbers Without A Third Variable

Destructuring Array Method (1)

So this array destructuring array method, also will be a one line swapping method. Here again we assigned the same values to a and b. Then we used [a, b] = [b, a], this should be easy to understand where first element’s value will be exchange with first value, same for second one as well. This is also considered as direct swap method. Here we created an array with two values a and b, when this [a,b] = [b,a]; line executes then the temporary array will form with b and a will be there. And as per array destructuring first element will assign to first element and second element will be assigned to second element.

So Basically a= b and b=a will be performed at the same time, so updation of value do not occur any problem in swapping.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var a = 10;
        var b = 2;
        document.write("Fourth Method </br>");
        [a,b] = [b,a]; //both values will be exchanged at same time
        document.writeln("value of a = "+a+"</br>");
        document.writeln("value of b = "+b+"</br>");
    </script>
    
</body>
</html>
Swap Two Numbers Without A Third Variable

Bonus Method

Okay, This method also a way to make this program, I don’t know what to call it, so simply it’s a bonus method. Here we again assigned the same value to a and b of course. And then we have used this a = (a*b)/(b=a); line of code to perform one line swapping. Here (a*b) will be 10×2 =20, and then we have simply assigned the value of a to b (b=a). Ultimately, (a*b)/(b=a) which is (20)/(10)= 2, so value of a is 2 and value of b will be 10.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var a = 10;
        var b = 2;
        document.write("Fifth Method </br>")
        a = (a*b)/(b=a); // 20/10
        document.writeln("value of a = "+a+"</br>");
        document.writeln("value of b = "+b+"</br>");
    </script>
    
</body>
</html>
Swap Two Numbers Without A Third Variable

You may also like:

  • How to Check If a Number is Positive, Negative, or Zero
  • How to Convert Kilometers to Miles and Celsius to Fahrenheit
  • How to Add Two Numbers, Swap Two Numbers And Find Square Root in JavaScript
  • Write a program to Check if a Number is Odd or Even in JavaScript

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

TAGGED: programs, Swap Two Numbers, Swap Two Numbers Without A Third Variable
Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Posted by Admin
Follow:
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
Previous Article Price Range Slider How to Make Price Range Slider Using JavaScript
Next Article How to Implement Class Inheritance in JavaScript How to Implement Class Inheritance in JavaScript?
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?