How to swap variables with destructuring in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Swapping variables has become very easy with destructuring. In contemporary javascript swapping takes place by using another variable. It may not be hectic but it is lengthy. But in modern javascript there is no need for the third variable. Let's discuss it in detail.

Example-1

In the following example, swapping has done using another variable called "temp". Therefore the code got lengthier. 

Live Demo

<html>
<body>
   <script>
      var a = "Sachin";
      var b = "Tendulkar";
      document.write("Before swapping-"+ " "+ a + " " +b);
      var tmp = a;
      a = b;
      b = tmp;
      document.write("</br>");
      document.write("After swapping-"+ " " + a + " " +b);
   </script>
</body>
</html>

Output

Before swapping- Sachin Tendulkar
After swapping- Tendulkar Sachin

The task of swapping has become easier because of destructuring. Here we don't need to use another variable and even the code is not lengthy.

Example-2

In the following example, no third variable is used and the swapping has done with destructuring. Here the code is much smaller than the above code.

Live Demo

<html>
<body>
   <script>
      var a = "Sachin";
      var b = "Tendulkar";
      document.write("Before swapping-"+ " "+ a + " " +b);
      [a,b] = [b,a];
      document.write("</br>");
      document.write("After swapping-"+ " " + a + " " +b);
   </script>
</body>
</html>

Output

Before swapping- Sachin Tendulkar
After swapping- Tendulkar Sachin
raja
Published on 16-Jul-2019 14:43:43
Advertisements