DEV Community

Van Balken
Van Balken

Posted on

A quick look at destructering

This post will use a couple of examples to provide a quick look at destructering In JavaScript (and TypeScript). You should read the MDN web docs if you want to know more. It's well-written and contains helpful examples.


The basics

Destructering is used to extract data from arrays ([]) and objects ({}) with little code:

const person = ['John', 25];

let name, age;

// Without destructuring
name = person[0];
age = person[1];

// With destructering
[name, age] = person;
const person = {name: 'John', age: 25};

const {name, age} = person;

Default values can be used as well:

const namelessPerson = {age: 21};

const {name = 'Jane Doe', age} = namelessPerson;

It can be used in a function to only pick the properties you need:

const person = {name: 'John', age: 25};

function hello({name}) {
    console.log(`Hello ${name}!`);
}

hello(person); // 'Hello John!'

A bad example

With the last two examples combined you can write code that is quite hard to read:

const person = {name: 'John', age: 25};
const namelessPerson = {age: 21};

function hello({name = 'Jane Doe'} = {name: 'John Doe'}) {
    console.log(`Hello ${name}!`);
}

hello(person); // 'Hello John!'
hello(namelessPerson); // 'Hello Jane Doe!'
hello(); // 'Hello John Doe!'

(Both the property name and the parameter object have default values assigned.)

An example in TypeScript

One specific situation in which destructering is useful is when you're subscribing to an observable that returns an array. For example when you use combineLatest:

combineLatest(user$, dog$).subscribe([user, dog] => {});

// And when explicitly typed
combineLatest(user$, dog$).subscribe([user, dog]: [User, Dog] => {});

Top comments (0)