JavaScript  

Destructuring in JavaScript

Introduction

If you’ve ever written something like const first = arr[0]; and thought "there's gotta be a cleaner way,” good news, there is, and it’s called destructuring.

What’s Destructuring?

Destructuring is just a fancy term for pulling values out of arrays or objects and sticking them into variables, all in one tidy line of code.

Destructuring Arrays

const [first, second, third] = ['red', 'green', 'blue'];

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

Skip Values

const [first, , third] = ['red', 'green', 'blue'];

console.log(first);  // red
console.log(third);  // blue
JavaScript

Set Defaults

const [x = 10, y = 20] = [];
console.log(x); // 10
console.log(y); // 20
JavaScript

Destructuring Objects

const { name, age } = {
    name: "Alice",
    age: 25,
    country: "USA"
  };

console.log(name); // Alice
console.log(age);  // 25
JavaScript

Rename While You’re At It

const { name: userName, country: userCountry } =  {
    name: "Alice",
    age: 25,
    country: "USA"
  };
console.log(userName); // Alice
console.log(userCountry); // USA
JavaScript

Give It a Default

const { city = "Unknown" } =  {
    name: "Alice",
    age: 25,
    country: "USA"
  };
console.log(city); // Unknown
JavaScript

Destructuring in Function Parameters

function showUser({ name, country }) {
  console.log(`${name} is from ${country}`);
}

const person = {
  name: "Bob",
  country: "France"
};

showUser(person); // Bob is from France
JavaScript

Quick Cheatsheet

// Array
const [a, b] = [1, 2];

// Object
const { x, y } = { x: 10, y: 20 };

// Rename
const { x: renamedX } = { x: 5 };

// Default
const { z = 100 } = {};
JavaScript

Conclusion

Destructuring is one of those features that might look “meh” at first, but once you start using it, you’ll never want to go back.