Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Object Destructuring in JavaScript

Object destructuring is a JavaScript assignment expression that makes it possible to extract values from the properties of an object into distinct variables. This feature was added in the ES6 version of JavaScript.

Need for Destructuring

Consider the following example. We extract the firstName & lastName from the person object and assign it to the firstName & lastName variable. As you can see that to extract values from the object, we need to assign one property at a time.

        
const person = {
  firstName: "Bill",
  lastName: "Gates"
};
 
//Without destructuring
 
let firstName=person.firstName;
let lastName=person.lastName;

                
        
    

The Destructuring assignment simplifies the above into a single line of code.

We place the variables inside the curly bracket separated by a comma and assign the object to it. The JavaScript looks in the object for the properties corresponding to the variable name and assigns its values to them.

        
const person = {
  firstName: "Bill",
  lastName: "Gates"
};
 
 
//destructuring assignment
let {firstName, lastName} = person;

                
        
    

Object Destructuring

The following is the Syntax of Object Destructuring in JavaScript

        
let {objectPattern1, objectPattern2, } = expression ;
 
                
        
    

Where

expression should evaluate an object. If the expression is not an object, then JavaScript will coerce it into an object.

objectPattern is the pattern that we use for destructuring. Since the expression is an object, we place the objectPattern inside the curly braces. Each Pattern is separated by a comma.

Extracting Properties

The following syntax shows how you can extract a property from an object.

        
let {propertyName1, propertyName2, } = <span style="background-color: inherit;">expression</span>;
                
        
    

Where propertyName1 & propertyName2 are the Properties of the object returned by the expression. The JavaScript creates the similarly named variables and assigns the value from the object to them

Following example extracts values of firstName & lastName properties of the person object into a firstName & lastName Variables.

        
const person = {
  firstName: "Bill",
  lastName: "Gates"
};
 
//object destructuring
let {firstName, lastName} = person;
 
console.log(firstName);  // Bill
console.log(lastName);  // Gates
                
        
    

Selectively Picking Values

You can selectively pick the values that you want to restructure. The following example extracts only the firstName & employer property from the person object.

        
const person =  {
    firstName:'Bill',
    lastName:'Gates',
    age:'50',
    employer:'Microsoft'
}
 
 
let { firstName, employer} = person
 
 
console.log(firstName)  //bill
console.log(employer)   //Microsoft
    
        
    

Aliases

Sometimes variables may have a different name than the property name. In such cases, you can use the aliases

The Syntax is as shown below. The propertyName1 is the name of the property that we want to extract. identifier1 is the variable where we want to store the value.

        
const { propertyName1: identifier1, propertyName2: alias2 } = expression;
    
        
    

The following example extracts the value from the name & employer property and assigns it to name & emp variable.

        
const person =  {
    firstName:'Bill',
    lastName:'Gates',
    age:'50',
    employer:'Microsoft'
}
 
 
let { firstName:name, employer:emp} = person
 
 
console.log(name)  //bill
console.log(emp)   //Microsoft
    
        
    

Default values

In the following example, we try to extract the age property. Since it does not exists in the person object it is initialed with undefined.

                            
const person =  {
    firstName:'Bill',
    lastName:'Gates',
}
 
 
let { firstName, age} = person
 
 
console.log(firstName)  //bill
console.log(age)   //undefined
 
  
    
        
    

In such situations, we can set the default value to the variable. The Destructuring assignment uses the default value in the following cases.

  1. If the property does not exist
  2. Property exists but its value is undefined.

The basic syntax for setting the default value is as a follows

                            
const { propertyName1=default1, propertyName2=default2 } = expression;
 
  
    
        
    

Where default1 & default2 are default values for the propertyName1 & propertyName2 respectively.

In the following example, we provide 0 as the default value for the age variable. The person object does not contain age property hence it sets the age variable value to 0.

                            
const person =  {
    firstName:'Bill',
    lastName:'Gates',
}
 
let { firstName, age=0} = person
 
console.log(firstName)  //bill
console.log(age)        //0      Uses default because age does not exists
 
  
    
        
    

If the age property exists and is undefined, then also it sets the age variable value to 0.

                            
const person =  {
    firstName:'Bill',
    lastName:'Gates',
    age:undefined
}
 
 
let { firstName, age=0} = person
 
 
console.log(firstName)  //bill
console.log(age)        //0
 
  
    
        
    

The basic syntax for setting the default value is as a follows

Expression as default value

You can also use any expression or function as a default value

                            
const person =  {
    firstName:'Bill',
    lastName:'Gates',
}
 
x=10
y=20
let { firstName, age=x+y} = person
 
 
console.log(firstName)  //bill
console.log(age)        //30
 
  
    
        
    

JavaScript function as default value.

                            
const person =  {
    firstName:'Bill',
    lastName:'Gates',
}
 
let { firstName, age=getAge()} = person
 
console.log(firstName)  //bill
console.log(age)        //50
 
function getAge() {
    return 50
}
 
  
    
        
    

The expression can also use the other variables in the pattern

                            
const person =  {
    a:10,
    b:20,
}
 
let { a, b,c=a+b} = person
 
console.log(c)    //30
 
  
    
        
    

Nested objects

We can also extract the properties from the nested objects.

Here is the basic syntax. The nestedObject is the property name of the nested object. Follow it up with a colon and curly braces. The nestedProperty1 ,nestedProperty2 Inside the curly braces refer to the properties of the nested object.

                            
const { nestedObject : { nestedProperty1, nestedProperty2,  }  } = expression; 
 
  
    
        
    

The employeer is a nested object inside the person object. We extract the values of name & country property from the employer object.

                            
const person =  {
    firstName:'Bill',
    lastName:'Gates',
    employeer : {
        name:'Micrsoft',
        country:'USA'
    }
}
 
let { firstName, employeer : { name , country } } = person
 
console.log(firstName)          //Bill
console.log(name)               //Microsoft
console.log(country)            //USA
    
        
    

You can also use the aliases & default values in the nested Destructuring assignment.

                            
const person =  {
    firstName:'Bill',
    lastName:'Gates',
    employeer : {
        name:'Micrsoft',
        country:'USA'
    }
}
 
let { firstName, employeer : { name:employerName , city="New York" } } = person
 
console.log(firstName)         //Bill
console.log(employerName)      //Microsoft
console.log(city)              //New York
    
        
    

Dynamic Properties

The object may have computed property names or we may add a new property dynamically. In such cases, the property name is known only at the runtime. We can use Object Destructuring to map to a dynamic property name.

The syntax for mapping a dynamic property is as follows. Instead of the property name, we use an expression inside the square brackets ([]). The expression must evaluate a string.

        
const { [expression]: identifier } = expression;
 
    
        
    

The following example shows how to map to a dynamic property name.

        

let prefix = "Book";
 
let book = {
    [ getAuthorName()]: 'Marijn Haverbeke',
    [ prefix + "Title"]: "Eloquent JavaScript",
    price:100
};
 
function getAuthorName() {
  return prefix+'Author'
}
 
 
priveVar="price";
 
let { [getAuthorName()]: author, [ prefix + "Title"] :title , [priveVar]:price } = book
 
 
console.log(author)   //Marijn Haverbeke
console.log(title)    //Eloquent JavaScript
console.log(price)    //100
 
 
    
        
    

Rest Operator

We can use the Rest Operator (... three full stops) to collect the remaining properties. The Rest operator must come last.

In the example below, ...otherinfo variable collects lastName & age as object.

                        
const person =  {
    firstName:'Bill',
    lastName:'Gates',
    age:60
}
 
let { firstName, ...otherinfo } = person
 
console.log(firstName)      //Bill
console.log(otherinfo)      //{lastName: "Gates", age: 60}    

                                    
                                

Rest Operator with the nested object.

                        
const person =  {
    firstName:'Bill',
    lastName:'Gates',
    employeer : {
        name:'Micrsoft',
        country:'USA'
    }
}
 
let { firstName, lastName, ...employerinfo } = person
 
console.log(firstName)         //Bill
console.log(lastName)          //Gates
console.log(employerinfo)      //{ employeer: {name: "Micrsoft", country: "USA"}  }  

                                    
                                

Read More

  1. JavaScript Tutorial
  2. Objects in JavaScript
  3. Create Objects in JavaScript
  4. Object Properties
  5. Computed Property Names
  6. Object Literal
  7. Constructor functions
  8. DefineProperty
  9. Property Descriptors Enumerable, Writable & Configurable
  10. Object Destructuring