
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swap Variables with Destructuring in JavaScript
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.
<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.
<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
Advertisements