What is array and object destructuring in JavaScript?

Array destructuring in JavaScript

Array destructuring is a unique way to extract an array’s value into new variables neatly.

Without using array destructuring, we would extract an array’s value into a new variable in the following way:

const profile = ["Nina", "Sarah", "Flora"];
const Name1 = profile[0];
const Name2 = profile[1];
const Name3 = profile[2];
console.log(Name1); // "Nina"
console.log(Name2); // "Sarah"
console.log(Name3); // "Flora"

Let’s now see the array destructuring equivalence of the snippet above:

const profile = ["Nina", "Sarah", "Flora"];
const [Name1, Name2, Name3] = profile;
console.log(Name1); // "Nina"
console.log(Name2); // "Sarah"
console.log(Name3); // "Flora"

Notice how we clean up our code by placing the three new variables (that is, Name1, Name2, and Name3) into an array object ([...]). We then assign them the profile array’s values.

In other words, we instruct the computer to extract the profile array’s values into the variables on the left-hand side of the assignment operatorhttps://codesweetly.com/javascript-statement/.

Object destructuring in JavaScript

Object destructuring is a unique way to extract an object’s value into new variables neatly.

Example

Without using object destructuring, we would extract an object’s value into a new variable in the following way:

const profile = {
Name1: "Nina",
Name2: "Sarah",
Name3: "Flora",
};
const Name1 = profile.Name1;
const Name2 = profile.Name2;
const Name3 = profile.Name3;
console.log(Name1); // "Nina"
console.log(Name2); // "Sarah"
console.log(Name3); // "Flora"

Let’s now see the object destructuring equivalence of the snippet above:

const profile = {
Name1: "Nina",
Name2: "Sarah",
Name3: "Flora",
};
const { Name1: Name1, Name2: Name2, Name3: Name3 } = profile;
console.log(Name1); // "Nina"
console.log(Name2); // "Sarah"
console.log(Name3); // "Flora"

Observe how we clean up our code by placing the three new variables into a properties object ({...}). We then assign them the profile object’s values.

In other words, we instruct the computer to extract the profile object’s values into the variables on the left-hand side of the assignment operator.

Keep in mind that in { Name1: Name1, Name2: Name2, Name3: Name3 }, the keys are references to the profile object’s properties. At the same time, the keys’ values represent our new variables.

The anatomy of a JavaScript object destructuring assignment

The following is a shorthand alternative to the previous snippet:

const profile = {
Name1: "Nina",
Name2: "Sarah",
Name3: "Flora",
};
const { Name1, Name2, Name3 } = profile;
console.log(Name1); // "Nina"
console.log(Name2); // "Sarah"
console.log(Name3); // "Flora"

Free Resources

Attributions:
  1. undefined by undefined
  2. undefined by undefined