From da161590f487f454f3148a1953a84324887bc4d6 Mon Sep 17 00:00:00 2001 From: wonderingabout Date: Wed, 29 Apr 2020 13:29:15 +0200 Subject: [PATCH] trick: use array destructuring to swap variables source: https://www.typescriptlang.org/docs/handbook/variable-declarations.html#array-destructuring --- .../10-destructuring-assignment/article.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/1-js/05-data-types/10-destructuring-assignment/article.md b/1-js/05-data-types/10-destructuring-assignment/article.md index 907c28cab3..54e87e6dd8 100644 --- a/1-js/05-data-types/10-destructuring-assignment/article.md +++ b/1-js/05-data-types/10-destructuring-assignment/article.md @@ -121,6 +121,23 @@ for (let [key, value] of user) { } ``` ```` + +### Swap variables + +It is also possible to use destructuring assignment to easily swap variables + +```js run +let a = "1"; +let b = "2"; +alert(`${a}, ${b}`); // 1, 2 + +[a, b] = [b, a]; +alert(`${a}, ${b}`); // 2, 1: successfully swapped! +``` + +The trick is that `a` and `b` values are assigned to a new array, from which `a` and `b` take their new values. +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. + ### The rest '...' 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 `"..."`: