Destructuring Assignment Cheat Sheet
13 июля 2024 г.
With destructuring assignment, variables are “extracted” from an object, string, or array.
They are declared using curly or square brackets, mirroring the structure of the object or array they are being extracted from.
Below are various examples using destructuring.
Destructuring and value manipulation:
JavaScript
1let [a, b] = [ 3, 5];2[a, b] = [a + 2, b + 8]; // a = 5; b = 13;3[a, b] = [b, a];4[a, b] // a = 13; b = 5;
Extra variables on the left are assigned undefined, while extra values on the right are ignored:
JavaScript
1const [f, n, k] = [2, 78]2console.log(f, n, k) // f = 2; n = 78; k = undefined;34const [c, o] = [1, 12, 96]5console.log(c, o) // c = 1; o = 12;
You can skip elements using extra commas:
JavaScript
1const [w,, e,, r] = [1, 12, 96, 2, 78, 79]2console.log(w, e, r) // w = 1; e = 96; r = 78;
Combining the remaining variables into one — the rest operator ...:
JavaScript
1const [t, ...u] = [1, 12, 96, 2, 78]2console.log(t, u) // t = 1; u = [ 12, 96, 2, 78 ];
Function return values:
JavaScript
1function getTrigonometric(x) {2 return [Math.sin(x), Math.cos(x)]3}4const [x, y] = getTrigonometric(129)5console.log(x, y) // x = -0.19347339203846847 y = -0.9811055226493881
In loops:
JavaScript
1const obj = {a: "one", b: "two"}2for(const [key, value] of Object.entries(obj)) {3 console.log(key, value)4}5// a one6// b two
Nested arrays:
JavaScript
1const [[i,d], [p,s]] = [[1, 12], [96, 2]]2console.log(i,d, p,s) // i = 1; d = 12; p = 96; s = 2;
Destructuring strings and objects:
JavaScript
1const [first, ...other] = "Moon";2console.log(first, other) // first = M; other = [ 'o', 'o', 'n' ];34const {min, max} = Math;5console.log(min(1, 4), max(8, 24)) // min - 1 max - 24
Renaming variables during destructuring:
JavaScript
1const object = {a: "your", b: "letter"}2const {a: one, b: two} = object;3console.log(one, two) //one = your; two = letter;