In this shot, we will learn how to swap variables using destructuring assignment in JavaScript. We will start with a problem statement, followed by an example.
Swap the two given variables using the JavaScript destructuring feature.
Input: x=5
, y=10
Output: x=10
, y=5
We will start solving this problem by looking at the destructuring concept.
JavaScript’s destructuring is used to unpack the values present in arrays or object properties into distinct variables.
//declare and initialize an arraylet arr = ["apple","orange"]//destructing the arrary arrlet [a,b] = arr//print a and b valuesconsole.log(a,b)
In the above code snippet:
arr
.arr
and store them in variables a
and b
.//given variableslet x = 5;let y = 10;console.log("Before:")console.log(x,y)//assign them as array to templet temp = [y,x];//destructure[x,y] = tempconsole.log("After:")console.log(x,y)
In the above code snippet:
x
and y
.x
and y
as an array in reverse order and assign it to temp
.temp
and assign it to x
and y
.