Destructuring~ Basics ~

Destructuring

I first saw destructuring in some other language. It took me some time to understand it, but once I got the idea, I couldn't stop thinking how nice will be to have it in JavaScript. A few months after that, it was introduced. The destructing is a JavaScript expression that extracts array items or object fields into individual variables. Here is how we destruct an object:

const user = { name: "Krasimir", job: "dev" };
const { name, job } = user;
console.log(`${name}, position: ${job}`); // Krasimir, position: dev

The other name of this assignment is "unpacking". As we can see here, the name and job fields are coming from the user object.

It works similarly with arrays:

// destructuring array
const arr = ["oranges", "apples", "bananas"];
const [a, b, c] = arr;
console.log(`I like ${a}`); // I like oranges

In the end, if we don't like the naming, we may create an alias. In the following example, name becomes who and job becomes position:

// destructuring with renaming
const user = { name: "Krasimir", job: "dev" };
const { name: who, job: position } = user;
console.log(`${who}, position: ${position}`); // Krasimir, position: dev