JavaScript Destructuring Pro Tips

Destructuring assignment is technique available in modern JavaScript and TypeScript that allows you to extract the values from an Object or Array, then assign them as variables. It can significantly improve the readability of your code in the right situation, so let’s take a look at scenarios where destructuring can save us a few lines of code.

Objects

Let’s imagine we have a big giant JSON response from an API, but only need a handful of its properties. Notice how we repeatedly call res.<somthing> - this can get ugly.

file_type_js_official object.js
const res = fetchBlogPost();

// 😒 Meh Code
const user = res.user;
const title = res.title;
const body = res.text;

// 🤯 Destructured Code
const { user, title, text } = res;

You can also use it with async/await.

async () => {
  const { user, text, title, date } = await fetchBlogPost();
}

And it comes in handy when using console.log because you can clearly name what you are logging.

// 😒 Meh Code
console.log(widget, component)

// 🤯 Destructured Code
console.log({ widget, component })
console log with destructuring

Function Arguments

Function arguments can also be destructured, which is especially useful when you have a large number of optional named arguments.

file_type_js_official function.js
// 😒 Meh Code
function bmi(person) {
    const height = person.height;
    const weight = person.weight;

    return weight / height;
}
// 🤯 Destructured Code
function bmi({ height, weight }) {
    return weight / height;
}

// Both are called the same way
bmi(person);

Arrays and Loops

Array destructuring is especially useful when you have an array where each position represents something meaningful. This data structure is similar to a tuple as in other languages like Python.

file_type_js_official array.js
const arr = ['jeff', 'delaney', 'js'];

// 😒 Meh Code
const first = arr[0];
const last = arr[1];
const lang = arr[2];

// 🤯 Destructured Code
const [first, middle, lang] = arr;

It is most powerful when you have a 2D array, or array-of-arrays. You can destructure the array positions while looping over the elements to write clean and readable code.

file_type_js_official loop.js
const peeps = [
    ['guido', 'van rossum', 'python'],
    ['brendan', 'eich', 'rust'],
];

for (const [first, middle, lang] of peeps) {
    console.log('hello ' + first);
}

More common than a 2D array is an array of objects. You can also loop over the key-value pairs in the object and destructure them along the way.

const animals = [
    { type: 'dog', name: '🐺 fido' },
    { type: 'cat', name: '🐱 snowball' }
];


for (const { name, type } of animals) {
    console.log(name, type);
}

You can even destrucutre nested properties on complex objects. In this case, each object has a friends Array and nested profile object. How do we assign values on the nested properties to variable names?

const animals = [
    { 
        type: '🐺 dog', 
        name: 'fido', 
        friends: ['rex', 'todd', 'bob'], 
        profile: { 
            color: 'brown',
            weight: 23 
        } 
    },
    { 
        type: '🐱 cat', 
        name: 'snowball', 
        friends: [ 'fido' ], 
        profile: { 
            color: 'white',
            weight: 7
        } 
    }
];


for (const { name, type, friends: [best], profile: { color } } of animals) {
    const bio = `${name} is a ${color} ${type} and his best friend is ${best}`
    console.log(bio);
}
complex loop destructuring assignment

Q&A Chat