Skip to main content

Command Palette

Search for a command to run...

02 - Destructuring | Let's break it down

no more obj.property headache

Updated
5 min read
02 - Destructuring | Let's break it down
S

Living an open source life!

Hello readers , welcome back to JS Extras!

In this series , we're covering JavaScript essentials.. the features that actually makes your life easier when you're building something.

Last time , we killed + with Template Literals.

Today, we're going to kill something even more annoying.. repetitive dot notation .

Let's get started.


So what's destructuring about ?

To understand this .. we'll first have to appreciate the mess it saves us from.

Let's say you have a user object

let user = {
    name : "binod" , 
    age : 24, 
    city : "forbesganj",
    email : "binod@example.com"
};
    

Now you want to use these values..

How would you do it ? Not a tough task right..

let userName = user.name; 
let userAge = user.age; 
let userCity = user.city; 
let userEmail = user.email;

console.log(`Hey \({userName}, you are \){userAge} years old from ${userCity}`);

so what is the problem ? if you think it's multiple dots .. then you're correct.

look at those 4 lines. Same thing repeated. user. everywhere.

It works . But its boring and messy.

And if you have 10 properties? RIP your fingers.

There is a better way for this too..


Destructuring

Here's the solution, and it's not complex..

Instead of writing user.name , user.age , user.city again and again..

you just do this :

let { name , age , city , email } = user;

console.log(`Hey \({name}, you are \){age} years old from ${city}`);

see , how did we reduce lines of code , without compromising the readability.

One line. All variables . Ready to use.

say good bye to multiple user.


How it works ?

Destructuring unpacks values from an object or array into variables.

The variable names must match the property names.

let user = { name: "binod", age: 24 };

let { name, age } = user;

console.log(name); // binod
console.log(age);  // 24

see? name becomes "binod" . age becomes 24.

Magic? No. it's just JavaScript being helpful ( for ones atleast )


What if you want different variable names ?

You can actually rename them.

let user = { name: "binod", age: 24 };

let { name: userName, age: userAge } = user;

console.log(userName); // binod
console.log(userAge);  // 24

name goes into userName and age into userAge.


Default values

Alright everything makes sense till here ..
but what if property doesn't exist?

That's where we use deault , means assign some default values if the property is non-existent

let user = { name: "binod" };

let { name="Unknown", city = "Unknown" } = user;

console.log(name); // binod
console.log(city); // Unknown

Arrays destructuring

Just like objects.. but one of the difference is

Objects use { } . Arrays use [ ]

let colors = ["red", "blue", "green"];

let [first, second, third] = colors;

console.log(first);  // red
console.log(second); // blue
console.log(third);  // green

and the fact that It works by position , not name ( another difference )

Want to skip an element ? Just leave a hole.

let colors = ["red", "blue", "green"];

let [first, , third] = colors; // see the gap b/w first and third

console.log(first); // red
console.log(third); // green

and that's how we skipped blue with an empty space b/w first and third.


Swapping made easy

Old way :

let a = 10;
let b = 20;

let temp = a;
a = b;
b = temp;

New way ;

let a = 10;
let b = 20;

[a, b] = [b, a];

console.log(a); // 20
console.log(b); // 10

Beautiful , One line .. no temp . ( Just like python. )


Where you'll actually use this

1. Function parameters

let user = { name: "binod", age: 24 };

Instead of this :

function showUser(user) {
  console.log(user.name, user.age);
}

Do this :

function showUser({ name, age }) {
  console.log(name, age); // no user. needed
}

Same result. Less typing. Clean code.

2. API responses (because APIs love sending objects)

let response = {
  status: 200,
  data: { user: "binod", id: 1 }
};

let { status, data } = response;
let { user, id } = data;

console.log(user); // binod

How simply we did restructure that.. dang.

3. Importing from modules ( you've probably seen this )

import { useState, useEffect } from "react";

Yes.. That's destructuring too.

You've been using it without even knowing. See? Maybe you're already a pro 😏.


Before vs After ( because visuals hit different )

1 line. Same result. Happier fingers.


Your turn real quick

Take this messy code :

let product = {
  title: "Wireless Mouse",
  price: 599,
  brand: "Logi"
};

let productTitle = product.title;
let productPrice = product.price;
let productBrand = product.brand;

Rewriting it with destructuring.

and One more for array.

let scores = [85, 92, 78, 95];
let firstScore = scores[0];
let secondScore = scores[1];

That's destructuring

Small feature. Huge quality of life upgrade.

Quick cheat sheet for you :

What you want How to write it
Object unpacking let { prop } = object
Array unpacking let [item] = array
Default value let { prop = "default" } = object
Renaming let { prop: newName } = object
Swap variables [a, b] = [b, a]

Alright.. that was it for this one


Next up in JS Extras : Spread vs Rest Operators - because ... does more than you think.

See you there!

signing off.

JS Extras

Part 1 of 2

After completion of basic javascript ! Here we gonna see extras.. that would a great addon to your exisiting javascript knowledge

Up next

01 - Template Literals in JS

no more + and quote cat-astrophe