Inspiration For Creative Minds
Home » Labs » Swap Variables in JavaScript – Example  

Filed under Labs

In simple words swapping means interchange the values. Here is a simple example which swap the values in variables a,b and the result of the function is given after code.

<html>
 <head>
 <script language="javascript">
 function showSwap()
 {
var a,b,c;
a=10;
b=20;
	document.write("Before Swapping");
	document.write("<br>");
	document.write("a="+a);
	document.write("<br>");
	document.write("b="+b);
	document.write("<br><br><br>");
c=a;
a=b;
b=c;
	document.write("After Swapping");
	document.write("<br>");
	document.write("a="+a);
	document.write("<br>");
	document.write("b="+b);
 }
 </script>
 </head>
 <body>
 <script language="javascript">
  showSwap();
 </script>
 </body>
 </html>

Output Will be

Before Swapping
a=10
b=20

After Swapping
a=20
b=10

It's only fair to share...Share on Google+Tweet about this on TwitterShare on Facebook
Labs

Posts you may like: