Hello Sunil
javascript-destructuring-assignment-feature-image

JavaScript ES6 : Master  Destructuring Assignment (Array & Object)

JavaScript ES6 provides a new feature called destructing assignment that allows you to destructure properties of an object or elements of an array into individual variables.

This article aims to show you exactly how array and object destructuring assignments work in JavaScript.

So, without any further ado, let’s first get started with array destructuring.

What Is Array Destructuring?

Array destructuring is a unique technique that allows you to neatly extract an array’s value into new variables.

For instance, without using the array destructuring assignment technique, you would copy an array’s value into a new variable like so:

const profile = ["Sunil", "Pradhan", "Bengaluru"];

const firstName = profile[0];
const lastName = profile[1];
const city = profile[2];

console.log(firstName); // Sunil
console.log(lastName); // Pradhan
console.log(city); // Bengaluru

Notice that the snippet above has a lot of repeated code which is not a DRY (Don’t Repeat Yourself) way of coding.

Let’s now see how array destructuring makes things more clean.

const profile = ["Sunil", "Pradhan", "Bengaluru"];

const [firstName, lastName, city] = profile;

console.log(firstName); // Sunil
console.log(lastName); // Pradhan
console.log(city); // Bengaluru

You see, like magic, we have cleaned up our code by placing the three new variables (that is, firstName, lastName, and city) into an array ([ ]). Then, we assigned them the profile array’s values.

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

Therefore, JavaScript will parse the profile array and copy its first value (“Sunil”) into the destructuring array’s first variable (firstName).

Likewise, the computer will extract the profile array’s second value (“Pradhan”) into the destructuring array’s second variable (lastName).

Lastly, JavaScript will copy the profile array’s third value (“Bengaluru”) into the destructuring array’s third variable (city).

Notice that the snippet above destructured the profile array by referencing it. However, you can also do direct destructuring of an array.

Let’s see how.

Direct Array Destructuring

JavaScript lets you destructure an array directly like so:

const [firstName, lastName, city] = [
  "Sunil", 
  "Pradhan", 
  "Bengaluru"
];

console.log(firstName); // Sunil
console.log(lastName); // Pradhan
console.log(city); // Bengaluru

Suppose you prefer to separate your variable declarations from their assignments. In that case, JavaScript has you covered. Let’s see how.

Assignment Separation From Declaration

Whenever you use array destructuring, JavaScript allows you to separate your variable declarations from their assignments.

let firstName, lastName, city;

[firstName, lastName, city] = ["Sunil", "Pradhan", "Bengaluru"];

console.log(firstName); // "Sunil"
console.log(lastName); // "Pradhan"
console.log(city); // "Bengaluru"

What if you want “Sunil” assigned to the firstName variable—and the rest of the array items to another variable? How you do that? Let’s find out below.

Assigning the Rest of an Array to a Variable

JavaScript allows you to use the rest operator (…) within a destructuring array to assign the rest of a regular array to a variable.

const [firstName, ...otherInfo] = ["Sunil", "Pradhan", "Bengaluru"];

console.log(firstName); // "Sunil"
console.log(otherInfo); // ["Pradhan", "Bengaluru"]

firstName takes the first value in the array, and by using the rest syntax, …otherInfo takes all the remaining values in the array as a new array of its own. Simple as that.

Always use the rest operator as the last item of your destructuring array to avoid getting a SyntaxError.

Now, what if you only want to extract “Bengaluru”? Let’s discuss the technique you can use below.

Ignoring Some Returned Values

Here’s how you can use array destructuring to extract values at any index position of a regular array:

const [, , city] = ["Sunil", "Pradhan", "Bengaluru"];

console.log(city); // "Bengaluru"

In the snippet above, we used commas to skip variables at the destructuring array’s first and second index positions.

By so doing, we were able to link the city variable to the third index value of the regular array on the right side of the assignment operator (that is, “Bengaluru”).

At times, however, the value you wish to extract from an array is undefined.

In that case, JavaScript provides a way to set default values in the destructuring array. Let’s learn more about this below.

Default Values & Array Destructuring Assignment

Setting a default value can be handy when the value you wish to extract from an array does not exist (or is set to undefined).

Here’s how you can set one inside a destructuring array:

const [firstName = "Guest", city = "Bengaluru"] = ["Sunil"];

console.log(firstName); // Sunil
console.log(city); // Bengaluru

In the snippet above, we set “Guest” and “Bengaluru” as the default values of the firstName and city variables.

Therefore, in our attempt to extract the first index value from the right-hand side array, the computer defaulted to “Bengaluru”—because only a zeroth index value exists in [“Sunil”].

So, what if you need to swap firstName’s value with that of city? Again, you can use array destructuring to get the job done. Let’s see how.

Swapping Variables

You can use the array destructuring assignment to swap the values of two or more different variables.

let firstName = "Sunil";
let city = "Bengaluru";

[firstName, city] = [city, firstName];

console.log(firstName); // Bengaluru
console.log(city); // Sunil

In the snippet above, we used direct array destructuring to reassign the firstName and city variables with the values of the array literal on the right-hand side of the assignment operator.

As such, firstName’s value will change from “Sunil” to “Bengaluru”. While city’s content will change from “Bengaluru” to “Sunil”.

Keep in mind that you can also use array destructuring to extract values from a regular array to a function’s parameters. Let’s talk more about this below.

Parsing an Array Returned from a Function

Here’s how you can use array destructuring to extract an array’s value to a function’s parameter:

// Define an array with two items:
const profile = ["Sunil", "Pradhan"];

// Define a function with one destructuring array containing two parameters:
function getUserBio([firstName, lastName]) {
  return `My name is ${firstName} ${lastName}.`;
}

// Invoke getUserBio while passing the profile array as an argument:
console.log(getUserBio(profile));

// The invocation above will return:
My name is Sunil Pradhan.

In the snippet above, we used an array destructuring parameter to extract the profile array’s values into the getUserBio’s firstName and lastName parameters.

Kindly note that an array destructuring parameter is typically called a destructuring parameter.

Here’s another example:

// Define an array with two string values and one nested array:
const profile = ["Bengaluru", "Male", ["Sunil", "Pradhan"]];

// Define a function with two destructuring arrays containing a parameter each:
function getUserBio([city, , [userName]]) {
  return `${userName} lives in ${city}`;
}

// Invoke getUserBio while passing the profile array as an argument:
console.log(getUserBio(profile));

// The invocation above will return:
Sunil lives in Bengaluru

In the snippet above, we used two array destructuring parameters to extract the profile array’s values into the getUserBio’s city and userName parameters.

There are times you may need to invoke a function containing a destructuring parameter without passing any argument to it.

In that case, you will need to use a technique that prevents the browser from throwing a TypeError.

Let’s learn about the technique below.

Without Supplying Any Argument

Consider the function below:

function getUserBio([firstName]) {
  console.log(
    "Do something else that does not need the destructuring parameter."
  );
  return `My name is ${firstName}.`;
}

Now, let’s invoke the getUserBio function without passing any argument to its destructuring parameter:

getUserBio();

After invoking the getUserBio function above, the browser will throw an error similar to TypeError: undefined is not iterable.

The TypeError message happens because functions containing a destructuring parameter expect you to supply at least one argument.

So, you can avoid such error messages by assigning a default argument to the destructuring parameter.

Here’s an example:

function getUserBio([firstName] = []) {
  console.log(
    "Do something else that does not need the destructuring parameter."
  );
  return `My name is ${firstName}.`;
}

Notice in the snippet above that we assigned an empty array as the destructuring parameter’s default argument.

So, let’s now invoke the getUserBio function without passing any argument to its destructuring parameter:

getUserBio();

The function will output:

"Do something else that does not need the destructuring parameter."
"My name is undefined."

Keep in mind that you do not have to use an empty array as the destructuring parameter’s default argument. You can use any other value that is not null or undefined.

So, now that we know how array destructuring works, let’s discuss object destructuring so we can see the differences.

What Is Object Destructuring?

Object destructuring is a unique technique that allows you to neatly extract an object’s value into new variables.

For instance, without using the object destructuring assignment technique, we would extract an object’s value into a new variable like so:

const profile = {
  firstName: "Sunil", 
  lastName: "Pradhan", 
  city: "Bengaluru"
};

const firstName = profile.firstName;
const lastName = profile.lastName;
const city = profile.city;

console.log(firstName); // Sunil
console.log(lastName); // Pradhan
console.log(city); // Bengaluru

Notice that the snippet above has a lot of repeated code which is not a DRY way of coding.

Let’s now see how the object destructuring assignment makes things neater and DRY.

const profile = {
  firstName: "Sunil", 
  lastName: "Pradhan", 
  city: "Bengaluru"
};

const { firstName: firstName, lastName: lastName, city: city } = profile;


console.log(firstName); // Sunil
console.log(lastName); // Pradhan
console.log(city); // Bengaluru

You see, like magic, we have cleaned up our code by placing the three new variables into a properties object ({}) and assigning them the profile object’s values.

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

Therefore, JavaScript will parse the profile object and copy its first value (“Sunil”) into the destructuring object’s first variable (firstName).

Likewise, the computer will extract the profile object’s second value (“Pradhan”) into the destructuring object’s second variable (lastName).

Lastly, JavaScript will copy the profile object’s third value (“Bengaluru”) into the destructuring object’s third variable (city).

Keep in mind that in { firstName: firstName, lastName: lastName, city: city }, the keys are references to the profile object’s properties – while the keys’ values represent the new variables.

Alternatively, you can use shorthand syntax to make your code easier to read.

const profile = {
  firstName: "Sunil", 
  lastName: "Pradhan", 
  city: "Bengaluru"
};

const { firstName, lastName, city } = profile;

console.log(firstName); // Sunil
console.log(lastName); // Pradhan
console.log(city); // Bengaluru

In the snippet above, we shortened { firstName: firstName, lastName: lastName, city: city} to { firstName, lastName, city}.

Observe that the snippets above illustrated how to assign an object’s value to a variable when both the object’s property and the variable have the same name.

However, you can also assign a property’s value to a variable of a different name.

Let’s see how.

Assigning to New Variable Names

JavaScript permits you to use object destructuring to extract a property’s value into a variable even if both the property and the variable’s names are different.

const profile = {
  firstName: "Sunil", 
  lastName: "Pradhan", 
  city: "Bengaluru"
};

const { firstName: fname, lastName: lname, city: town } = profile;

console.log(fname); // Sunil
console.log(lname); // Pradhan
console.log(town); // Bengaluru

In the snippet above, the computer successfully extracted the profile object’s values into the variables named fname, lname, and town —even though the properties and variables are of different names.

Kindly note that, const { firstName: fname} = profile is equivalent to const fname = profile.firstName.

Here’s another example:

const profile = {
  lastName: { familyName: "Pradhan" }
};

const { lastName: { familyName: surname } } = profile;

console.log(surname); // Pradhan

In the snippet above, the computer successfully extracted the profile object’s value into the surname variable—even though the property and variable are of different names.

Kindly note that const { lastName: { familyName: surname } } = profile is equivalent to const surname = profile.lastName.familyName.

Notice that so far, we have destructured the profile object by referencing it. However, you can also do direct destructuring of an object.

Let’s see how.

Direct Object Destructuring

JavaScript permits direct destructuring of a properties object like so:

const { firstName, lastName, city } = {
  firstName: "Sunil", 
  lastName: "Pradhan", 
  city: "Bengaluru"
};

console.log(firstName); // Sunil
console.log(lastName); // Pradhan
console.log(city); // Bengaluru

Suppose you prefer to separate your variable declarations from their assignments.

In that case, JavaScript has you covered. Let see how.

Assignment Without Declaration

Whenever you use object destructuring, JavaScript allows you to separate your variable declarations from their assignments.

// Declare three variables:
let firstName, lastName, city;

// Extract values to the three variables above:
({ firstName, lastName, city } = {
  firstName: "Sunil", 
  lastName: "Pradhan", 
  city: "Bengaluru"
});

// Invoke the three variables:
console.log(firstName); // Sunil
console.log(lastName); // Pradhan
console.log(city); // Bengaluru

Here you need to make sure that you encase the object destructuring assignment in parentheses. By so doing, the computer will know that the object destructuring is an object literal, not a block.

Place a semicolon (;) after the parentheses of an object destructuring assignment.

By doing so, you will prevent the computer from interpreting the parentheses as an invocator of a function that may be on the previous line.

What if you want “Sunil” assigned to the firstName variable—and the rest of the object’s values to another variable? How can you do this?

Let’s find out below.

Rest Syntax in Object Destructuring

JavaScript allows you to use the rest operator(…) within a destructuring object to assign the rest of an object literal to a variable.

Here’s an example:

const { firstName, ...otherInfo } = {
  firstName: "Sunil",
  lastName: "Pradhan",
  city: "Bengaluru"
};

console.log(firstName); // "Sunil"
console.log(otherInfo); // {lastName: "Pradhan", city: "Bengaluru"}

Always use the rest operator as the last item of your destructuring object to avoid getting a SyntaxError.

At times, the value you wish to extract from a properties object is undefined.

In that case, JavaScript provides a way to set default values in the destructuring object.

Let’s learn more about this below.

Default Values & Object Destructuring Assignment

Setting a default value can be handy when the value you wish to extract from an object does not exist (or is set to undefined).

Here’s how you can set one inside a destructuring properties object:

const { firstName = "Guest", city = "Bengaluru" } = {
  firstName: "Sunil"
};

console.log(firstName); // Sunil
console.log(city); // Bengaluru

In the snippet above, we set “Guest” and “Bengaluru” as the default values of the firstName and city variables.

Therefore, in our attempt to extract the second property’s value from the right-hand side object, the computer defaulted to “Bengaluru”—because only a single property exists in {firstName: “Sunil”}.

So, what if you need to swap firstName’s value with that of city? Again, you can use object destructuring to get the job done. Let’s see how below.

Swapping Variables

You can use the object destructuring assignment to swap the values of two or more different variables.

let firstName = "Sunil";
let city = "Bengaluru";

({ firstName, city } = {firstName: city, city: firstName});

console.log(firstName); // Bengaluru
console.log(city); // Sunil

The snippet above used direct object destructuring to reassign the firstName and city variables with the values of the object literal on the right-hand side of the assignment operator.

As such, firstName’s value will change from “Sunil” to “Bengaluru”. While city’s content will change from “Bengaluru” to “Sunil”.

Keep in mind that you can also use object destructuring to extract values from properties to a function’s parameters.

Let’s talk more about this below.

Unpacking Fields from Objects Passed as Function Parameters

Here’s how you can use object destructuring to copy a property’s value to a function’s parameter:

// Define an object with two properties:
const profile = {
  firstName: "Sunil",
  lastName: "Pradhan",
};

// Define a function with one destructuring object containing two parameters:
function getUserBio({ firstName, lastName }) {
  return `My name is ${firstName} ${lastName}.`;
}

// Invoke getUserBio while passing the profile object as an argument:
console.log(getUserBio(profile));

// The invocation above will return:
My name is Sunil Pradhan.

In the snippet above, we used an object destructuring parameter to copy the profile object’s values into getUserBio’s firstName and lastName parameters.

Kindly note that an object destructuring parameter is typically called a destructuring parameter.

Here’s another example:

// Define an object with three-parent properties:
const profile = {
  city: "Bengaluru",
  gender: "Male",
  fullName: {
    firstName: "Sunil",
    lastName: "Pradhan"
  }
};

// Define a function with two destructuring objects containing a parameter each:
function getUserBio({ city, fullName: { firstName: userName } }) {
  return `${userName} lives ${city}`;
}

// Invoke getUserBio while passing the profile object as an argument:
console.log(getUserBio(profile));

// The invocation above will return:
Sunil lives Bengaluru

In the snippet above, we used two destructuring parameters to copy the profile object’s values into getUserBio’s city and userName parameters.

There are times you may need to invoke a function containing a destructuring parameter without passing any argument to it.

In that case, you will need to use a technique that prevents the browser from throwing a TypeError.

Let’s learn about the technique below.

Invoke a Function Containing Destructured Parameters Without Supplying Any Argument

Consider the function below:

function getUserBio({ firstName }) {
  console.log(
    "Do something else that does not need the destructuring parameter."
  );
  return `My name is ${firstName}.`;
}

Now, let’s invoke the getUserBio function without passing any argument to its destructuring parameter:

getUserBio();

After invoking the getUserBio function above, the browser will throw an error similar to TypeError: (destructured parameter) is undefined.

The TypeError message happens because functions containing a destructuring parameter expect you to supply at least one argument.

So, you can avoid such error messages by assigning a default argument to the destructuring parameter.

Here’s an example:

function getUserBio({ firstName } = {}) {
  console.log(
    "Do something else that does not need the destructuring parameter."
  );
  return `My name is ${firstName}.`;
}

Notice that in the snippet above, we assigned an empty object as the destructuring parameter’s default argument.

So, let’s now invoke the getUserBio function without passing any argument to its destructuring parameter:

getUserBio();

The function will output:

"Do something else that does not need the destructuring parameter."
"My name is undefined."

Keep in mind that you do not have to use an empty object as the destructuring parameter’s default argument. You can use any other value that is not null or undefined.

Conclusion

Array and object destructuring is something’s existed in languages like Perl and Python for a good bit of time, but it wasn’t until ECMAScript 2015 that JavaScript began to get some parity in this area.

So JavaScript Destructuring makes it possible to unpack values from arrays, or properties from objects, into distinct variables. 

We hope this tutorial provides a clear understands of how Destructuring works in JavaScript. Happy Coding.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.