What is destructuring in JavaScript?

What is destructuring in JavaScript?

What is the destructuring syntax?

As per MDN:

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Let's try to understand what that means. The key points to keep in mind are destructing assignment is a JavaScript expression (all expressions evaluate to a value), it unpacks properties as individual items and it does not modify the original entity when we unpack properties.

In JS, related properties are grouped in the form of an object or array. An object contains related data that can be accessed with a key and an array contains related data stored in a sequence.

let obj = {
id:1,
name:"jay",
age:22
}

let arr = [1,2,3,4,5,6]

Using destructuring we can conveniently unpack properties from an array/object and use the specific properties as needed.

there are two patterns of destructuring: binding pattern and assignment pattern.

in the binding pattern, the unpacked object/array properties are bound to variables with the let/const/var keyword. this creates a separate copy of the unpacked properties

let obj = {
name:"jay",
city:"mumbai"
}

let {name, city} = obj

in the assignment pattern, we unpack the properties and assign them to the target. this target can be an array item or object property.

const cities = []
const person = {
    name:"jay",
    firstCity:"pune",
    secondCity: "mumbai"
};

({firstCity: cities[0], secondCity: cities[1]} = person)
console.log(cities) //[ 'pune', 'mumbai' ]

one gotcha to keep in mind when using destructuring with an assignment pattern is we need to wrap the destructuring code block with parentheses () if we are using destructing the assignment without let/const declaration.

key features of destructuring

Let us see a few key points around the destructuring syntax.

we can destructure any iterable

Iterables in javascript are objects that represent a collection of items and can be iterated over using for..of the loop.

//array destructuring
const arr = [1,2,3,4,5]
let [firstArrItem, secondArrItem, thirdArrItem] = arr

//object destructuring
const obj = {
  id: 1,
  firstName:"jay",
  lastName: "rajput"
}

// destructuring with map data structure
const map = new Map()
map.set(1, "one")
map.set(2,"two")
let [firstMapItem, secondMapItem] = map
console.log(firstMapItem, secondMapItem)
//[1,"one"] [2, "two"]

//destructing with set

let newSet = new Set([1,2,3,3,4,5,6,6,7])
let [firstSetItem, secondSetItem, ...rest] = newSet
console.log(firstSetItem, secondSetItem, rest)
// 1 2 [ 3, 4, 5, 6, 7 ]

destructuring does not modify the original entity

When we use destructuring assignment we unpack the iterable properties as a separate copy. we do not modify the original entity

const arr = [1,2,3,4,5]

const [one, two, three, four, five]  = arr

console.log(arr) //[ 1, 2, 3, 4, 5 ]

console.log(one, two, three, four, five) //1 2 3 4 5

we can skip destructured items using commas

Since the unpacking of list items takes place in sequence, we can skip any value in between by writing empty values between commas

const arr = [1,2,3,4,5]

// we skip the second value below by leaving it empty. 
const [one, , three, four, five]  = arr

console.log(arr)  //[ 1, 2, 3, 4, 5 ]

console.log(one, three, four, five) //1 3 4 5

discarding unwanted properties and using the rest operator (...) to group values

if the destructuring assignment variables on the left are less than the original item we are trying to destructure, the remaining values are discarded. If we do not want to discard them, we can group them using the rest operator into a group (array/object).

if we are destructuring an array, the remaining items are grouped into an array. In the case of the object, the remaining values are grouped into an object.

the point to remember is rest operator should be the last item in destructuring assignment.


//object
let obj = {
  id: 1,
  name:"jay rajput", 
  city: "mumbai",
  age: 18,
}

let {id, name} = obj // city and age property are discarded
console.log(id, name)  //1 'jay rajput'

//city and age are grouped into object named remaining
let {id:newId, name:newName, ...remaining} = obj
console.log(newId,newName, remaining) //1 'jay rajput' { city: 'mumbai', age: 18 }



//array
let arr = [1,2,3,4,5,6]
// group the remaining items from array into rest variable
let [first, second, ...rest] = arr
console.log(first, second, rest)  //1 2 [ 3, 4, 5, 6 ]

renaming object destructed assignments

We can rename destructed assignments with a different name to avoid conflicting variable names


const obj = {
  id:1,
  firstname:"jay",
  lastName:"rajput",
  role:"developer",
  city:"mumbai"
}

//unpack role property from obj and rename it to jobTitle
const {role:jobTitle } = obj

console.log(jobTitle)    //'developer'

nested destructuring

if we have a nested object then we can pull the nested properties too using destructuring assignment syntax.


const obj = {
  id:1,
  firstname:"jay",
  lastName:"rajput",
  role:"developer",
  address:{
    city:"mumbai",
    state:"maharashtra"
  }
}

//destructure nested property city and rename it to myCity
const {address:{city:myCity}} = obj

console.log(myCity)      //'mumbai'

As we can see from the above examples destructuring syntax is a usefule ES6 feature. When working with a JS framework/library, it is common to see the destructuring syntax. We destructure the data received from an API or the data that is passed to the component as a parameter.