Destructuring arrays and objects
Another powerful construct provided by JS nowadays is the destructuring assignment. This is also harder to explain than to show, so once again let's directly get to some examples! The simplest case lets you split an array into variables:
let [a, b, c] = [22, 9, 60]; // a=22, b=9, c=60
More interesting still is that you can swap or twiddle variables around! Following on from the preceding example, we'd have the following:
[a, b] = [b, a]; // a and b are swapped! a=9, b=22
[c, b, a] = [b, a, c]; // and now a=60, b=9, c=22
You can also assign default values to missing variables, ignore values you don't care for, and even apply the rest operator:
// default values
let [d, e = 1, f = 2, g] = [12, 4]; // d=12, e=4, f=2, g=undefined
// ignoring values
let [h, , i] = [13, 21, 34]; // h=13, i=34
// using with rest
let [j, k, ...l] = [2, 3, 5, 8]; // j=2, k=3, l=[5,8]
This can also be applied to objects, letting you pick attributes and even renaming them, as with the flag and name in the following code. Assigning values by default is also possible:
let obj = { p: 1, q: true, r: "FK" };
let { p, r } = obj; // p=1, r="FK"
let { q: flag, r: name } = obj; // Renaming: flag=true, name="FK"
let { q, t = "India" } = obj; // q=true; t="India"
One interesting usage of this is allowing a function to return many values at once. If you want to return, say, two values, you can either return an array or an object and use destructuring to separate the returned values in a single sentence:
function minAndMax1(...nums) {
return [Math.min(...nums), Math.max(...nums)];
}
let [small1, big1] = minAndMax1(22, 9, 60, 12, 4, 56);
Alternatively, you can use an object and an arrow function just for variety; note the extra parentheses we used, since we are returning an object. We are also renaming attributes, by the way:
const minAndMax2 = (...nums) => ({
min: Math.min(...nums),
max: Math.max(...nums)
});
let { min: small2, max: big2 } = minAndMax2(22, 9, 60, 12, 4, 56);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment