Javascript - Object Destructuring Syntax

Introduction

The Object Destructuring syntax is,

var { a: a, b: b, c: c } = {a: 1, b: 2, c: 3}; 

Here, we used the same name for the variables being assigned and the properties of the returned object.

They do not have to be the same, you can use any name for the local variables being assigned.

In case they are the same, the syntax can be further shortened by leaving out the "a: " part of the notation.

This declaration statement can simply be written as,

var { a, b, c } = {a: 1, b: 2, c: 3}; 
console.log( a, b, c );             // 1 2 3 

Consider the following example,

var { a: foo, b: bar, c: baz } = {a: 1, b: 2, c: 3}; 

console.log( foo, bar, baz );         // 1 2 3 
console.log( a, b, c );               // ReferenceError 

Consider the following assignment:

var foo = 42, bar = 100; 

var obj = { a: foo, b: bar }; 
var { a: FOO, b: BAR } = obj; 

console.log( FOO, BAR );              // 42 100 

Here, a and b refer to the properties of the object and in the object destructuring assignment statement.

a and b also represent the object properties.

Using Object Destructuring, you can actually set the value of multiple variables using the same property value.

var { x: foo, x: bar } = { x: 42 }; 

console.log( foo );  // 42 
console.log( bar );  // 42 

A right-hand side is required for the destructuring statement.

var { x, y };         // syntax error! 
let { x, y };         // syntax error! 
const { x, y };       // syntax error! 

All of the above declarations result in a syntax error because of a missing initializer in the destructuring declaration.

Related Topic