Skip to content

Commit 3a3086b

Browse files
committed
minor fixes
1 parent ef71488 commit 3a3086b

File tree

1 file changed

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

1 file changed

+12
-10
lines changed

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

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -122,21 +122,23 @@ for (let [key, value] of user) {
122122
```
123123
````
124124

125-
### Swap variables
126-
127-
It is also possible to use destructuring assignment to easily swap variables
125+
```smart header="Swap variables trick"
126+
A well-known trick for swapping values of two variables:
128127
129128
```js run
130-
let a = "1";
131-
let b = "2";
132-
alert(`${a}, ${b}`); // 1, 2
129+
let guest = "Jane";
130+
let admin = "Pete";
131+
132+
// Swap values: make guest=Pete, admin=Jane
133+
[guest, admin] = [admin, guest];
133134
134-
[a, b] = [b, a];
135-
alert(`${a}, ${b}`); // 2, 1: successfully swapped!
135+
alert(`${guest} ${admin}`); // Pete Jane (successfully swapped!)
136136
```
137137

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.
138+
Here we create a temporary array of two variables and immediately destructure it in swapped order.
139+
140+
We can swap more than two variables this way.
141+
```
140142
141143
### The rest '...'
142144

0 commit comments

Comments
 (0)