Destructuring

A JavaScript expression that allows you to unpack values from arrays or properties from objects into distinct variables in a concise syntax.

Overview

Destructuring assignment is a special syntax that allows you to extract multiple values from arrays or objects and assign them to variables in a single statement. It makes code more readable and concise, especially when working with function parameters, API responses, or complex data structures.

Example

javascript
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first = 1, second = 2, rest = [3, 4, 5]

// Object destructuring
const user = { name: 'Alice', age: 30, city: 'NYC' };
const { name, age } = user;
// name = 'Alice', age = 30

// Function parameters
function greet({ name, age }) {
  console.log(`${name} is ${age} years old`);
}

greet(user);

// Nested destructuring
const { address: { street } } = person;

Key Points

  • Works with arrays and objects
  • Can provide default values
  • Can skip elements in arrays
  • Can rename variables during destructuring
  • Commonly used with function parameters

Learn More