Destructuring of arrays is a very useful tool in modern JS programming since it saves time and decreases code bloat.
// Destructure an array const arr = [val1, val2, val3, val4]; const [var1, var2, var3, var4] = arr;
We can also destructure only part of an array or switch the order of variables after destructuring.
const arr = [val1, val2, val3, val4]; const [var1, , , var4] = arr;
Notice that for switching order using destructuring notation, we need to declare the variables into which we destructure using 'let' and not 'const' (because in essence, we change their values on reordering values).
const arr = [val1, val2, val3, val4]; let [var1, var2, var3, var4] = arr; // destructure [var4, var3, var2, var1] = [var1, var2, var3, var4] // change order
If we by some reason destructure into more variables we can assign default values to avoid undefined values.
const arr = [val1, val2, val3, val4]; // set the spare variable to have the value 1 after destructuring const [var1, var2 , var3 , var4, var5 = 1] = arr;
Destructuring objects is very much like array, with slight differences in syntax.
If we use the first variant of destructuring, we must make sure that the variable names into which we destructure are the exact same as the properties of the object being destructured.
// Destructure an object const {prop1, prop2, prop3} = obj;
The second variant allows us to destructure into custom names variable names.
const {prop1:var1, prop2:var2, prop3:var3} = obj;
The same technique for assigning default values to variables in array destructuring applies to object destructuring (let's say, in cases where we are not sure a property exists).
Also, destructuring nested objects is similar in form as done with arrays.
Destructuring of objects can be done into function parameters as well (which is useful for end users using an API, since the value copying is done not by order, but by property keys).