filmov
tv
Swapping🔁 two values using Destructuring in JS #coding #javascript #arrays

Показать описание
Today, I will show you how you can swap the values of two variables in JavaScript without using a third variable and that too in just a single line of code. In my previous short I showed you guys the solution to this problem using basic arithmetic operations but it took 3 lines of code to perform the swap, but there is a much easier way to do this using destructuring in JavaScript. So First let us understand the syntax destructuring arrays in Javascript and then we will apply the same principle to solve this problem. Let's say we have an array called numbers with the integers 2 and 5, now we want to assign these two values present inside this array to two different variables. With destructuring, we can easily extract values from this array into individual variables lets say by the name of a and b by writing the names of the variables inside square brackets just like we normally do for arrays on the left side of the assignment operator and on the right side provide the array name numbers. Now when we log the values of these 2 variables you will notice that a was assigned the value 2 and b the values 5. Now using this same syntax of destructuring we can also swap two value of two variables by simply exchanging the order in which the values to need to be extracted. So on the right side of the assignment operator, we will first create our array of these two values by placing them inside square brackets and then on the left side while destructuring we will simply swap the order like this. Now we log our two variables you will see that the values were actually swapped.
Комментарии