Destructuring is a special syntax to extract the values from enumerable types and assign them to a variable.

Let’s see an example

Javascript Destructuring and objects

An object extracted by key and assigned to variables of the same key

const employee = {name: 'john', salary: 5000}
const {name,salary} = employee
console.log(name) // john
console.log(salary) // 5000

Javascript destructuring an array

Array elements are extracted into variables without using index syntax(array[index]). The original array was not modified with this assignment.

const numbers = [11, 21, 31]
const [first, second, third] = number
console.log(first, second, third) // 11, 21, 31

ES6 deep nested object destructuring

sometimes, the Object contains nested objects.

In the example, the Employee object contains simple keys and nested object(roles). The object contains top-level (name, salary, roles) and nested-level (id, role) keys.

Top-level keys are extracted using const {name, salary} = employee

Similarly, Nested keys are extracted using syntax

const { roles: { id,role }, } = employee;
const employee = {
  name: 'john', salary: 5000, roles: {
    id: 1,
    role: "sales"
  }
}
const { name, salary } = employee
console.log(name) // john
console.log(salary) // 5000

const { roles, roles: { id, role }, } = employee;
console.log(roles) // {id: 1, role: "sales"}
console.log(id, role) // john

## ES6 deep nested object contains array destructuring

Below Object is a nested object, that contains a nested array of objects..

const employee = {
  name: 'john', salary: 5000,
  attributes: {
    group: [{
      groupId: 1
    }]
  }
}
const { name, salary } = employee
console.log(name) // john
console.log(salary) // 5000

let { attributes, attributes: { group: [{ groupId }] } } = employee
console.log(attributes)

console.log(groupId) // 1

Output:

{
    group: [{
      groupId: 1
    }]
}