Array Destructuring

Destructuring has become a major language feature in JavaScript, most prominently seen with imports, but also in function declarations and so on.  While object literals are the usual case for destructuring, remember that you can also destructure Arrays and Sets. Let’s have a look at how destructuring is used for arrays and Sets!

The usual case for destructuring is with an object literal:

const dict = { prop1: "one", prop2: "two" }; const { prop1, prop2 } = dict;
// prop1 = "one"
// prop2 = "two"

The syntax for Array and Set destructuring is a bit different:

const arr = ["uno", "dos"]; const [one, two] = arr;
// one = "uno"
// two = "dos" // Or more explicitly
const [width, height] = [200, 400];

The destructuring syntax within iteration looks like:

const items = [ ["one", "two"], ["three", "four"]
items.forEach(([uno, dos]) => { console.log(uno, dos);
}); // "one", "two"
// "three", "foor"

You can also clone an array with destructuring:

const arr = ["one", "two"];
const clone = [..arr];

Destructuring is awesome for skilled JavaScript developers and can be confusing to newcomers.  Basic array destructuring doesn’t mislead too much but iterating can be an ugly snippet.  Taking a minute to see these reduced examples may help you too better understand the pattern.

Related Post

Rojenx is a leading concept artist who work appears in games and publications

Check out his personal gallery here

In other news …