DEV Community

Cover image for Understanding the Destructuring assignment in JavaScript
Brandon Damue
Brandon Damue

Posted on

Understanding the Destructuring assignment in JavaScript

I needed a refresher on a few JavaScript features and concepts, so I went to do some reading on a couple of them. In today's article, we are going to be looking at the Destructuring Assignment. If you are not already aware, it is one of the many features for working with arrays and objects that was introduced to JavaScript in ES6(the 2015 edition of JavaScript). This article is a succinct collection of the knowledge I have gathered from various resources on the topic of interest. Without any further long talk, let's get to business!

What is Destructuring?

The Destructuring assignment syntax is a JavaScript expression that allows you to unpack values from arrays, or properties from objects, into distinct variables. Destructuring does not mean “destructive” or "destroyed". It’s called “destructuring assignment” because it “destructurizes” by copying items into variables. The original array or object itself remains unmodified. Destructuring can greatly reduce the lines of code necessary to manipulate data in these structures. There are two types of destructuring: Object destructuring and Array destructuring:

Object Destructuring

Object destructuring allows you to create new variables using an object property as their values. Consider the following example; an object representing a student with an id, name and dateOfBirth.

const student = {
  id: 53783,
  name: 'Maxwell Johson',
  dateOfBirth: '08/05/1997',
}
Enter fullscreen mode Exit fullscreen mode

Traditionally, if you were to create a new variable for each property, you would have to assign each variable individually which is a lot of repetition if you ask me. Take a lot at what I'm talking about:

// Create variables from Object properties
const id = student.id
const name = student.name
const dateOfBirth = student.dateOfBirth
Enter fullscreen mode Exit fullscreen mode

With object destructuring, this can all be done in a single line of code. By enclosing each variable in curly brackets {}, JavaScript will create new variables from each property with the same name:

const { id, name, dateOfBirth } = student
Enter fullscreen mode Exit fullscreen mode

Log these value to a console and you'll see that the values of the variables are the values of the properties of the student object.

It is important to note that destructuring an object does not effect a change on the original object(i.e the original object is not modified). If you call the original student object you'll see that it's properties are unchanged.

The default assignment for object destructuring creates new variables with the same name as the object property. If you do not want the new variable to have the same name as the object property, you have the option of giving the new variable a different name by using a colon (:) to decide the name, as seen in the following example:

var student = {    // Object we want to destructure
    id: 4678,
    name: 'Dave Smalls',
    dateOfBirth: '01/09/2003'
};

// Destructuring the object into variables with
// different names than the object variables
var { id: studentId, name: studentName, dateOfBirth: dob } = student;
console.log( studentId, studentName, dob);
Enter fullscreen mode Exit fullscreen mode

We can also assign default values to variables whose property may not exist in the object we want to destructure. This will prevent the variable from having an undefined value assigned to it. The code below demonstrates this:

var student = {    // Object we want to destructure
    id: 4678,
    name: 'Dave Smalls',
    dateOfBirth: '01/09/2003'
};

// Destructuring the object into variables without 
// assigning default values 
var { name, dateOfBirth, nationality } = student;
console.log("Without setting default values")
console.log(name, dateOfBirth, nationality);

// Destructuring the object into variables by 
// assigning default values 
var { name = 'default name', 
      dateOfBirth = 'default date of birth', 
      nationality = 'default nationality' } = student;
console.log("\n After setting default values")
console.log( name, dateOfBirth, nationality);
Enter fullscreen mode Exit fullscreen mode

Pros of Object Destructuring

  1. It allows us to write code that is more succint, since it allows us to bundle variables inside one object and then access the individual elements in another function without needing to use the dot notation.

  2. It makes sure the code doesn't break in case a value is missing since it allows us to set default values for specific variables

  3. When working with large frameworks that pass objects to functions with a lot of values, if we only need one or two values, we can destructure it. This helps make the code easier to work with.

Cons

Using object destructuring in JavaScript has some cons too. Some of them are:

  1. If an object has a lot of variables, it becomes very tedious to destructure it. In this case, use the dot notation.

  2. In case an object is different from what was expected and we don't account for that, it might result in bugs in the code.

Array Destructing

Array destructuring allows you to create new variables using an array item as a value. The syntax of Array Destructuring is as follows:

// we have an array with the name and surname
var arr = ["John", "Doe"]

// destructuring assignment
// sets firstName = arr[0]
// and surname = arr[1]
var [firstName, surname] = arr;

console.log(firstName); // John
console.log(surname);  // Smith
Enter fullscreen mode Exit fullscreen mode

As you can see, the syntax is pretty simple. It’s just a shorter way to write the following:

// var [firstName, surname] = arr;
var firstName = arr[0];
var surname = arr[1];
Enter fullscreen mode Exit fullscreen mode

In array destructuring, unwanted items of the array can also be thrown away by adding an extra comma. See the example below:

// second element is skipped by using an extra comma
var [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];

console.log( title ); // Consul
Enter fullscreen mode Exit fullscreen mode

In the code above, the second item of the array is skipped, the third one is assigned to title, and the rest of the array items are also skipped as there are no variables for them.

If the array we want to destructure is shorter than the list of variables on the left, there’ll be no errors. Absent values are assigned undefined:

var [firstName, surname, age] = ['Julius', 'Caesar'];

console.log(firstName); // Julius
console.log(surname); // Caesar
console.log(age); // undefined
Enter fullscreen mode Exit fullscreen mode

If we want a default value to replace the missing one, we can provide it using =:

// default values
let [name = "Bruno", surname = "Anonymous"] = ["Julius"];

console.log(name);    // Julius (from array)
console.log(surname); // Anonymous (default used)
Enter fullscreen mode Exit fullscreen mode

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

Conclusion

The fact that many other programming languages do not have a corresponding syntax for destructuring might give this feature a learning curve both for new JavaScript developers and those coming from another language. Be persistent and as time goes by, you'll get the hang of it. Hope to meet you soon in another article.

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Great article, you got my follow, keep writing!

Collapse
 
brandondamue profile image
Brandon Damue

Thank you Al. Your comment is highly appreciated.