JavaScript Destructuring

Master object and array destructuring for cleaner variable assignment and function parameters.

TL;DR

  1. 01Extract object properties into variables with curly brace syntax.
  2. 02Extract array elements into variables with square bracket syntax.
  3. 03Use default values when properties or elements are missing.

Tips

  1. 01Use destructuring in function parameters to document what properties a function expects, making code more readable and self-documenting.
  2. 02Combine destructuring with rest syntax to pull out a few named values while collecting the remaining properties into one object.
  3. 03Rename destructured variables to avoid naming collisions when two objects in the same scope share a property name.

Warnings

  1. 01Destructuring doesn't create new properties on objects — it just assigns values to variables in the local scope.
  2. 02Destructuring a null or undefined value throws a TypeError immediately, so guard against missing data before destructuring it.
  3. 03Default values only apply when a property is undefined, so a falsy value like false or 0 still wins.

Object Destructuring

    Basic extraction

    Extract properties from an object into separate variables.

    const user = { name: "Alice", age: 30 };
    const { name, age } = user;
    console.log(name); // "Alice"
    Exact key match

    Property names must match the object keys exactly.

    const { name, email } = user;
    // name is available, but email is undefined
    Extract only what you need

    Destructure only the properties you need from an object.

    const { name } = user;
    // age is not extracted
    Renaming

    Use shorter or clearer variable names with renaming.

    const { name: userName, age: userAge } = user;
    Nested objects

    Destructure nested objects by continuing the pattern.

    const user = { profile: { name: "Alice" } };
    const { profile: { name } } = user;

Array Destructuring

    Position-based extraction

    Extract array elements into separate variables by position.

    const colors = ["red", "green", "blue"];
    const [first, second, third] = colors;
    console.log(first); // "red"
    Skipping elements

    Skip elements by leaving the position empty.

    const [first, , third] = colors;
    // second is not assigned
    Rest syntax

    Use rest syntax to capture remaining elements.

    const [first, ...rest] = colors;
    // first = "red", rest = ["green", "blue"]
    Nested arrays

    Destructure nested arrays the same way as nested objects.

    const matrix = [[1, 2], [3, 4]];
    const [[a, b], [c, d]] = matrix;
    Swapping variables

    Swap variables without a temporary variable.

    let x = 1, y = 2;
    [x, y] = [y, x]; // x = 2, y = 1

Default Values

    Basic defaults

    Provide default values for properties that might be missing.

    const { name = "Guest", email = "no-email" } = {};
    console.log(name); // "Guest"
    Works with arrays too

    Defaults work with both objects and arrays.

    const [first = "a", second = "b"] = [];
    // first = "a", second = "b"
    Undefined only

    Defaults are used only if the value is undefined, not falsy.

    const { count = 0 } = { count: false };
    // count = false, not 0
    Defaults in parameters

    Use defaults with function parameters for required values.

    function greet({ name = "Guest" } = {}) {
      console.log(`Hello ${name}`);
    }
    greet(); // "Hello Guest"
    Renaming plus defaults

    Combine renaming and defaults in one destructuring expression.

    const { name: userName = "Anonymous", age: userAge = 0 } = {};
    console.log(userName); // "Anonymous"
    console.log(userAge);  // 0

Function Parameters

    Destructured object params

    Destructure objects directly in function parameters.

    function displayUser({ name, age }) {
      console.log(`${name} is ${age}`);
    }
    displayUser({ name: "Alice", age: 30 });
    Destructured array params

    Destructure arrays in function parameters the same way.

    function sum([a, b]) {
      return a + b;
    }
    sum([1, 2]); // 3
    Default params

    Use default parameters together with destructuring.

    function greet({ greeting = "Hello" } = {}) {
      console.log(greeting);
    }
    greet(); // "Hello"
    Self-documenting

    This pattern makes function signatures self-documenting.

    Shape validation

    Destructuring in parameters forces the caller's data to have the expected shape.

Advanced Patterns

    Computed property names

    Extract a property using a dynamic key with computed property names.

    const key = "name";
    const { [key]: value } = { name: "Alice" };
    Collect remaining properties

    Extract named properties and collect the rest into a new object.

    const { name, ...rest } = { name: "Alice", age: 30, city: "NYC" };
    // rest = { age: 30, city: "NYC" }
    Rename plus defaults

    Rename multiple properties and set defaults in the same pattern.

    const { name: n = "Guest", age: a = 0 } = user;
    Deeply nested aliases

    Destructure deeply nested paths with renaming in a single expression.

    const {
      profile: {
        contact: { email }
      }
    } = user;

In Practice

FAQ