Skip to content

Commit da16159

Browse files
1 parent 889913d commit da16159

File tree

1 file changed

+17
-0
lines changed
  • 1-js/05-data-types/10-destructuring-assignment

1 file changed

+17
-0
lines changed

1-js/05-data-types/10-destructuring-assignment/article.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,23 @@ for (let [key, value] of user) {
121121
}
122122
```
123123
````
124+
125+
### Swap variables
126+
127+
It is also possible to use destructuring assignment to easily swap variables
128+
129+
```js run
130+
let a = "1";
131+
let b = "2";
132+
alert(`${a}, ${b}`); // 1, 2
133+
134+
[a, b] = [b, a];
135+
alert(`${a}, ${b}`); // 2, 1: successfully swapped!
136+
```
137+
138+
The trick is that `a` and `b` values are assigned to a new array, from which `a` and `b` take their new values.
139+
This is much easier than using a temporary value to store a value until one of the variables is assigned the new value, then assign the temporary value to the other variable.
140+
124141
### The rest '...'
125142

126143
If we want not just to get first values, but also to gather all that follows -- we can add one more parameter that gets "the rest" using three dots `"..."`:

0 commit comments

Comments
 (0)