

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to 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
- Related Questions & Answers
- How to swap variables using Destructuring Assignment in JavaScript?
- How to Swap Two Variables using Python?
- What is JavaScript object Destructuring?
- Destructuring and function parameters in JavaScript
- How to swap two String variables without third variable.
- Swap two variables in one line in Java
- How to pass JavaScript Variables with AJAX calls?
- Swap two variables in one line using C#
- Swap two variables in one line in C/C+
- Swap two variables in one line in using Java
- Swap two variables in one line in using Python?
- How to declare variables in JavaScript?
- How to name variables in JavaScript?
- How to declare global Variables in JavaScript?
- How to declare String Variables in JavaScript?
Advertisements