A practical guide to object destructuring in JavaScript

A practical guide to object destructuring in JavaScript

Learn JavaScript object destructuring with lots of examples and use-cases. Understanding the destructuring concepts will make you super productive.

ยท

9 min read

Object in JavaScript is used to store multiple values as a complex data structure. We create objects with curly braces({...}) and one or more properties separated by comma(,) symbols. Each of the properties is a key-value pair separated by the colon(:) symbol. The key must be a string or JavaScript Symbol type. The value can be of any type, including another object.

Here is an example of an object with six properties. The value of the name key is of type string whereas, and it is a number for the age and std keys. The subjects key value is an array. The value of parents and address are objects.

const student = {
 'name': 'John Williamson',
 'age': 9,
 'std': 3,
 'subjects': ['Maths', 'English', 'EVS'],
 'parents': {
   'father': 'Brown Williamson',
   'mother': 'Sophia',
   'email': 'john-parents@abcde.com'
 },
 'address': {
   'street': '65/2, brooklyn road',
   'city': 'Carterton',
   'country': 'New Zealand',
   'zip': 5791
 }
}

Please note: We will use this student object in the various examples below.

Object Destructuring

We store data in objects to retrieve it based on needs at a later point in time. For example, if we want to retrieve the value of the name and city information from the student object, we can do,

const name = student.name;
const city = student.address.city;
console.log(name, city); // John Williamson Carterton

It works but with a bit more work. First, we use the dot(.) notation to access the values. We also need to declare a couple of variables to assign the values accordingly.

We can simplify the value retrieval from the JavaScript objects using the Object Destructuring syntax. It is a new syntax introduced in EcmaScript version 6(ES6). It helps to retrieve values from the object property and assign them to variables.

The expression to retrieve the name property value from the student object using object destructuring is the following,

const {name} = student;
console.log(name); // John Williamson

On the left side of the expression, we use the object property key(in this case, it is name) and place it inside the {}. It also becomes the variable name to hold the property value. We mention the const, let keywords to define the variable scope. No separate variable declaration is required.

On the right side of the expression, we use the actual object to retrieve the value.

destructure_2.png

So, how do we retrieve more than one property value using object destructuring? We keep adding the object keys inside the {} on the left side of the expression. In the example below, we retrieve name, age, and std information from the student object using object destructuring syntax.

const {name, age, std} = student;
console.log(name, age, std); // John Williamson 9 3

Have you noticed, we have saved ourselves from writing a couple of extra lines of code here?

Add a New Variable with a Default Value

We have seen, object destructuring simplifies the property value retrieval with the new syntax. But it is not limited to just that. We can add a brand new variable while destructuring, optionally with a default value. In the example below, the meal variable is non-existent in the student object. But we can add it in the object destructuring expression and add a default value to it.

const {name, std, meal='bread'} = student;
console.log(meal); // bread

How do you achieve the same otherwise? Here is the alternate code where you need to check a condition and assign.

let meal = student.meal ? student.meal : 'bread';

New Variable with a Computed Value

In the example above, we have created a new variable and assigned a constant value(bread). We can also assign a value computed from other destructured variables from the same object.

Here is an example where we have added a new variable called numberOfSubjects and assigned a value computed using another property's(subjects) value.

const {subjects, numberOfSubjects=subjects.length} = student;
console.log(numberOfSubjects); // 3

Add Aliases using Destructuring

We can give an alias name to our destructured variables. It is useful when there are chances of variable name conflicts.

In the example below, we have specified an alias name for the property, std as standard.

const {std: standard} = student;
console.log(standard); // 3

A point to note here. If we try to access the std variable after assigning the alias, we will get a ReferenceError saying, std is not defined. Hence once we create an alias, we can access the property value only using the alias name.

alias reference error

Nested Object Destructuring

A nested object has one or more property values as objects. The student object we are using in this article is a nested object. It has two properties, address and parents have object values.

const student = {
.....
'parents': {
   'father': 'Brown Williamson',
   'mother': 'Sophia',
   'email': 'john-parents@abcde.com'
 },
 'address': {
   'street': '65/2, brooklyn road',
   'city': 'Carterton',
   'country': 'New Zealand',
   'zip': 5791
 }
.....
}

So far, we have seen examples of retrieving non-object key values. We can go deep nested in the hierarchy to retrieve any object key values from any depth using destructuring. In the example below, we have retrieved the zip value from the address property of the student object.

We are already aware of how to retrieve the value of the address key,

const {address} = student;

Here is the output if we log the address variable in the console,

Logging Address to the console

But we are interested in the zip value and we want it in one step. Let's use destructuring,

const {address : {zip}} = student;
console.log(zip); // 5791

You can go to any depth like this. You need to always start with the top level and go down in the hierarchy until you reach the value you want to retrieve.

Destructure to the Function Parameters

We can write precise and smart code using object destructuring and pass as function parameters. Let us understand it with an example. The usual student object is like,

const student = {
 'name': 'John Williamson',
 'age': 9,
 'std': 3,
 'subjects': ['Maths', 'English', 'EVS'],
 'parents': {
   'father': 'Brown Williamson',
   'mother': 'Sophia',
   'email': 'john-parents@abcde.com'
 },
 'address': {
   'street': '65/2, brooklyn road',
   'city': 'Carterton',
   'country': 'New Zealand',
   'zip': 5791
 }
}

Let's assume we have a function that sends an email to the student's parent(note, there is an email property under the parents property). This function also logs a statement for a successful email sent.

So, we can call the function like,

sendEmail(student);

We can use destructuring to pass the email value to the function definition. There is no need to pass the entire student object and then retrieve the required value inside the function.

const sendEmail = ({parents: {email}}) => {
  console.log(`Sent email to ${email}`);
}

Please note, we have performed the nested object destructuring in the above function to retrieve the email value.

Destructure Function Return Value

In JavaScript, a function may return an object. When we call that function, we may not be interested in the entire object but its specific property values. Here is another opportunity to use object destructuring.

In the example below, the function getStudent returns an object,

const getStudent = () => {
 return {
    'name': 'John Williamson',
     'age': 9,
     'std': 3,
     'subjects': ['Maths', 'English', 'EVS'],
     'parents': {
       'father': 'Brown Williamson',
       'mother': 'Sophia',
       'email': 'john-parents@abcde.com'
     },
     'address': {
       'street': '65/2, brooklyn road',
       'city': 'Carterton',
       'country': 'New Zealand',
       'zip': 5791
     }
 }
}

We are only interested in name and subject key values. We can retrieve them using the destructuring expression,

const { name, subjects } = getStudent();
console.log(name, subjects);

The output,

Object Destructuring Function Return

Destructure within the Loop

Object destructuring comes in handy when we need the object key values within a loop. We can use destructuring with the for-of loop using a simple syntax. Let's take an array of students. To keep it simple, each of the student objects has only two properties, name and grade.

const students = [
    {
        'name': 'William',
        'grade': 'A'
    },
    {
        'name': 'Tom',
        'grade': 'A+'
    },
    {
        'name': 'Bob',
        'grade': 'B'
    }
];

Now, we will use the for-of loop to iterate over the students array and retrieve the values from each of the student objects. To do that, we can use object destructuring as,

for(let {name, grade} of students){
 console.log(`${name} has got the grade ${grade}`);
}

The output,

Students Grade

Destructuring using Dynamic Name Property

In many cases, you may not know the key of an object's property in advance. You may only know it at the run time of the code execution. In those cases, you can not hard-code the key name to retrieve the value using object destructuring.

For example, let us take a function getStudentInfo that takes a key as a parameter and returns the corresponding value from the object.

getStudentInfo('name'); // Returns, John Williamson
getStudentInfo('age'); // Returns, 9

The parameter passed to the function getStudentInfo is dynamic. Hence to use object destructuring with the dynamic keys, we need to enclose the key with a pair of square brackets([...]).

const getStudentInfo = key => {
  const {[key]: value} = student;
  return value;
}

Omitting the square brackets in the above code would result in the undefined value.

A Few Tips about Object Destructuring

Object destructuring is an exciting inclusion to the JavaScript programming language. As you have seen so far, there are many possibilities to use in our day-to-day programming using JavaScript. Here are a few tips you may find helpful.

  • The let, const keywords have a significant role in the object destructuring syntax. Omitting them in the code syntax will end up in error, Uncaught SyntaxError: Unexpected token '='.

    // Don't do this
    {name} = student; // Uncaught SyntaxError: Unexpected token '='
    

    Even if you declare the variable in advance and try to use it later in the destructuring syntax, it will result in a similar error.

    let name;
    {name} = student; // Uncaught SyntaxError: Unexpected token '='
    

    In case you have to omit the let, const keywords, you have to put the destructuring expression inside the parenthesis ((...)).

    let name;
    ({ name  } = student);
    console.log(name); // John Williamson
    
  • Object destructuring syntax may be a bit hard to remember. It is okay if you do not remember it ultimately. It is usual. You can refer to any guide like this one to get the syntax and use it.


I hope you enjoyed this article or found it helpful. Let's connect. You can find me on Twitter(@tapasadhikary) sharing thoughts, tips, and code practices. Please hit the Subscribe button at the top of the page to get an email notification on my latest posts.

๐Ÿ‘‹ Do you have further questions on Object Destructuring? Are you looking for a 1-1 session on this topic? You can reach out to me for a chat or call. Please check my availability on Hire the Author.

You may also like,

P.S. I love Coffee โ˜•. Buy Me A Coff

Did you find this article valuable?

Support Tapas Adhikary by becoming a sponsor. Any amount is appreciated!