Code Synopsis logo

What is Object Destructuring in JavaScript ES6

Arrays and objects are entities, and the term “destructuring” describes disassembling an entity. Let’s assume we start with an object containing three properties:

const myApple = { color: "red", size: "large", weight: "8 oz" };

To disassemble the object, we can assign each property to a variable. This gives us properties we can modify without modifying the original object:

let color = myApple.color; let size = myApple.size; let weight = myApple.weight; color = "green"; console.log(color); // green console.log(myApple.color); // red

As you can see, we needed a separate line of code to disassemble each property. Consequentially, disassembling a large object would require many lines of code. The destructuring syntax available with ES6 gives us a shorthand. Here’s how it looks for the same three properties:

let {color, size, weight} = myApple; color = "green"; console.log(color); // green console.log(myApple.color); // red

You can also use destructuring to disassemble an array:

const arr = ['joe', 'ben']; let [ person1, person2 ] = arr; person1 = 'allen'; console.log(person1); // allen console.log(arr[0]); // joe

Learn to recognize the destructuring syntax by the position of the assignment operator. Note the difference between:

let = [];

and:

let [] = arr;

Destructuring works with any variable assignment, but since it is an ES6 syntax, use it with let if you plan to modify the values and const if you don’t plan to change them.

Again, use square brackets to destructure from an array and curly braces to destructure from an object. You can rename destructured properties this way:

let {color: hue, size, weight} = myApple; console.log(hue); // red

It’s important to understand that the destructuring syntax assigns values to variables. If you already defined variables with the same names, you would have a collision.

let color = blue; let {color, size, weight} = myApple; // ERROR: Identifier 'color' has already been declared

You don’t have to worry about the order or quantity of properties when destructuring an object, and you can extract only what you need:

const {size} = myApple; console.log(size); // 8 oz

Related posts:

Helpful references:

Have feedback on this topic?