Skip to main content

Command Palette

Search for a command to run...

Destructuring in JavaScript

Published
3 min read
Destructuring in JavaScript

When we work with arrays and objects in JavaScript, we often need to take values out of them.

Normally we do something like:

const user = {
  name: "Dhiraj",
  age: 20
}

const name = user.name
const age = user.age

Works fine.

But it feels repetitive.

So JavaScript gives us a cleaner way to do this.

That is destructuring.

In this blog I will share how I understand destructuring and how it makes code simpler.


What destructuring means

Destructuring means:

taking values out of an array or object and assigning them to variables

In short:

extract → assign


Destructuring objects

Instead of this:

const user = {
  name: "Dhiraj",
  age: 20
}

const name = user.name
const age = user.age

We can do:

const { name, age } = user

That’s it.

less code, same result


How it actually feels

Object → variables


Important thing

Variable name must match key:

const { name } = user

takes user.name


Destructuring arrays

Arrays work a bit differently.

const arr = [10, 20, 30]

const [a, b, c] = arr

So:

  • a = 10

  • b = 20

  • c = 30

Here it depends on position.


Array mapping idea


Skipping values

const arr = [10, 20, 30]

const [a, , c] = arr

skips middle value


Default values

Sometimes value may not exist.

const user = {
  name: "Dhiraj"
}

const { name, age = 18 } = user

if age not present → use default


Before vs After

Before:

const title = post.title
const author = post.author
const date = post.date

After:

const { title, author, date } = post

cleaner, less repetition


Benefits of destructuring

  • reduces repetitive code

  • makes code cleaner

  • easier to read

  • faster to write


Small real example

function greet(user) {
  const { name } = user
  console.log("Hi " + name)
}

Even shorter:

function greet({ name }) {
  console.log("Hi " + name)
}

Where you will see it a lot

  • React props

  • API responses

  • function parameters

  • arrays from functions


Destructuring is just a cleaner way to take values out of arrays and objects.

Once you start using it, going back feels weird.

It doesn’t add new power, just makes things simpler.