GUIDE: Array And Object Destructuring

❯❯ How To Destructure Arrays

Destructuring of arrays is a very useful tool in modern JS programming since it saves time and decreases code bloat.

Destructure an array into discrete variables
click to copy code segment
//  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.

Partly destructure an array
click to copy code segment
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).

Switch order of vars after destructuring
click to copy code segment
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.

Destructuring with default values
click to copy code segment
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;

                              

❯❯ How To Destructure Objects

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 into discrete variables
click to copy code segment
//  Destructure an object
const {prop1, prop2, prop3} = obj;

                              


The second variant allows us to destructure into custom names variable names.

Destructure an object into custom named variables
click to copy code segment
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).

profile picture

WHO AM I?

Teacher
Thinker
Tinkerer