Wednesday, July 17

Destructuring Assignment In JavaScript

I’m not so sure, but I think JavaScript might be the only web technology where you can destructure objects and assign the individual units in one take. It is also one great feature that allows you can get straight to the point with what you have to do and keep things very clean.

Destructuring assignment in more simple words means unpacking the values of objects or arrays into simple variables. You have probably already seen it used somewhere, and it never made sense to you. At the end of this guide, we will see how to use it and what it can replace for you.


Let’s Start With Arrays

Old school ways tell us that if we have an array and we want to assign some of it’s values to variables, we do something like this:

let johnDoe = ["John", "Doe", "Iskolo"]
let firstName = johnDoe[0]
let lastName = johnDoe[1]
let title = johnDoe[2]

console.log(firstName, lastName, title) // John Doe Iskolo

But would you not like to do this instead?

let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName, title] = johnDoe
console.log(firstName, lastName, title) // John Doe Iskolo

The best part is that you can pick any number of elements you want

let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName] = johnDoe
console.log(firstName, lastName) // John Doe


let johnDoe = ["John", "Doe", "Iskolo"]
let [, lastName, title] = johnDoe
console.log(lastName, title) // Doe Iskolo

We can do it with strings as well

let [firstName, ,title] = "John Doe Iskolo".split(" ")
console.log(firstName, title) // John Iskolo

We can throw in the rest operator to collect the rest ?

let [firstName, ...others] = "John Doe Iskolo".split(" ")
console.log(firstName, others) // John Iskolo

And we can even bring in objects here

let johnDone = {}
[johnDoe.first, johnDoe.last] = "John Doe Iskolo".split(" ")
console.log(johnDoe.first, johnDoe.last) // John Doe

In Looping Through Objects
We can use it in looping through a key-value pair variable like an object or map. Here is what is very common:

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
Object.keys(obj).forEach(key => {
  console.log(`${key} : ${obj[key]}`)

We can spin that differently like this:

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
for(let [key, value] of Object.entries(obj)) {
  console.log(`${key} : ${value}`)

It might look like the same thing to you, but it is not. In using forEach above, we pull the keys of the object into an array, then looping through that array of keys now and using those keys to pick out the values of objects. Phew! I lost my breath for a second reading that ?.

In the second part, we just go straight and loop through each object entries and extracting the keys and values.

Assigning default values
We can assign defaults values, just for a situation where the variable we wish to destructure is empty

let [firstName = "John", ,title = "Fire"] = "John Doe".split(" ")
console.log(firstName, title) // John Fire

Now To Objects

Like we did with arrays, we can destructure objects as well. If you have ever used React, you are likely to have seen this used when importing a module.

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"

let {firstName, lastName) = obj
console.log(firstName, lastName) // John Doe

When destructuring objects, we use the keys as variable names. This is how JavaScript knows which property of the object you want to assign. Unlike arrays where you use their index/positions in the assignment, here you use the keys.

This destructuring works on any kind of object. If your object has nested values, you can still destructure that and extract the values into variables.

let obj = {
  name : "John Doe",
  address : {
    city : "Omsk",
    country : "Russia"
let {city, country} = obj.address
console.log(city, country) // Omsk Russia

Using It To Pass Function Arguments

Let’s be frank, you might have seen functions that look like this:

function sumFunc(a = true, b = "", c = "", d = 0, e = false) {
// Call the function
sumFunc(true, "", "", "", true)
// Or if we want to preserve default values
sumFunc(true, undefined, undefined, undefined, true)

It doesn’t look so good. It gets worse if you are trying to perform a function like making a chart and you need a lot of arguments (think like 15 optional arguments) to create the chat. It is plainly unsustainable.

Let destructuring save the day ?

function sumFunc({a = true, b = "", c = "", d = 0, e = false}) {
let args = {a : false, e: true}
// Call the function

By passing the function arguments as an object, they will get automatically resolved into independent arguments. Now, we pass an object with matching key-value pairs and the function will work nicely.

Admit it, you love the destructured way ?.


Destructuring is an operation you can do without, however, you can already see how it makes you a better developer. Cleaner code, fewer repetitions and more structure over what you have.

Use destructuring today and make your code a better code ?.


0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x