Skip to main content

Command Palette

Search for a command to run...

Destructuring in JavaScript

Updated
8 min readView as Markdown
Destructuring in JavaScript

What destructuring means

In JavaScript, destructuring is a special syntax that allows you to "unpack" values from arrays or properties from objects and assign them directly to separate variables.

Instead of writing multiple lines of code to access data using indexes or dot notation, you can extract everything you need in a single statement.

1. Object Destructuring

This allows you to pull properties out of an object by their key names.

  • Basic Example:

    javascript

    const user = { name: "Alice", age: 25 };
    const { name, age } = user; // name = "Alice", age = 25
    

    Use code with caution.

Renaming: You can assign a property to a variable with a different name using a colon.

javascript

const { name: userName } = user; // userName = "Alice"

Use code with caution.

2. Array Destructuring

This extracts values from an array based on their position (index).

  • Basic Example:

    javascript

    const colors = ["red", "green", "blue"];
    const [first, second] = colors; // first = "red", second = "green"
    

    Use code with caution.

Skipping Items: Use commas to skip specific elements.

javascript

const [,, third] = colors; // third = "blue"

Use code with caution.

3. Key Advanced Features

  • Default Values: You can set a fallback value in case the property or element is undefined.

    javascript

    const { city = "New York" } = user; 
    

    Use code with caution.

  • Rest Pattern (...): Collects the remaining properties or elements into a new object or array.

    javascript

    const [head, ...tail] = [1, 2, 3, 4]; // tail = [2, 3, 4]
    

    Use code with caution.

  • Nested Destructing: You can extract data from deeply nested structures by mirroring their shape on the left side of the assignment.

Why Use It?

  • Cleaner Code: Reduces repetitive code like const name = user.name; const age = user.age;.

  • Function Parameters: It is highly useful in React props or function arguments to see exactly what data a function expects.

  • Immutability: Destructuring does not modify the original array or object; it simply copies the values into new variables.

Destructuring arrays

Array destructuring is a feature that lets you extract values from arrays into variables easily.

Instead of accessing values using indexes repeatedly:

const arr = [10, 20, 30];

const a = arr[0];
const b = arr[1];

👉 You can use destructuring.

Basic syntax

const numbers = [10, 20, 30];

const [a, b, c] = numbers;

console.log(a);
console.log(b);
console.log(c);

Output

10
20
30

How it works

Values are assigned based on position:

a → first element
b → second element
c → third element

Skipping elements

const colors = ["red", "green", "blue"];

const [first, , third] = colors;

console.log(first);
console.log(third);

Output

red
blue

Swapping variables

Very common interview question 👇

let x = 5;
let y = 10;

[x, y] = [y, x];

console.log(x, y);

Output

10 5

Using rest operator

const nums = [1, 2, 3, 4, 5];

const [a, b, ...rest] = nums;

console.log(a);
console.log(b);
console.log(rest);

Output

1
2
[3, 4, 5]

Default values

const arr = [1];

const [a, b = 100] = arr;

console.log(a);
console.log(b);

Output

1
100

Real-world use cases

  • Returning multiple values from functions

  • React hooks:

    const [state, setState] = useState();
    
  • API response handling

  • Cleaner code

Visual idea

https://images.openai.com/static-rsc-4/ZxK_LxDjnK0VCfQ2dRnqsFp0Z1vsUxc2HiJfYy0AdMjXgUq90CnrfiKR6MvKliCcAb-CxQejcr_tdgQRLV-Co8ATOZVUpS_LUSDqsDAA1uiQWyNTaFWI5qIN9aWV2h5Xzdwltju8ESpy4B8vS-SArr7VV_vyzXfoxD9GJD1sBXABHh58OhICrnv3VNbo0d7U?purpose=fullsize https://images.openai.com/static-rsc-4/r2G_7VxR0-vwZZVHp7E2Dk27MM3kkjbS0iMDv4DeK2ZnpqM2BN63LwRbNb7C9Qv3wVLOrHGP-cDg0XFgSn8G0uIyFPv0WwmSdU5m1l5Q4KwV9hbl9oU5iK09-_a3ISnnsYY2VEr6XP8i-nT62bnzGxj9zqFEq-SN-ADIRRmLSDk9lX_EFYPVbcZErRiPcz7t?purpose=fullsize https://images.openai.com/static-rsc-4/4e5RH3ctNngzSCQCJEzSrZ5CAqLF1-btp6xxLfUhoYucsdpHyC9LLuJHw4sZMwdn8VYX76PP-vnHvDMO4AwyGznA5Ue6Yqi3M9Xj82NdphEVvyN70-xYnCNncx1JNe7FqGFDIOfGpXCSGqE2vYl1oZGifGZf5J1kh9We2wF6Lxf4tsKkRR3Sh-EXfQF_LPKo?purpose=fullsize

Destructuring objects

Object destructuring is a JavaScript syntax introduced in ES6 that allows you to extract values from objects and bind them to variables in a single step. It essentially "unpacks" properties by matching the shape of the object on the left side of the assignment.

Basic Syntax

The most common form uses curly braces {} to extract properties by their key names.

javascript

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

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

Use code with caution.

Key Features

  • Renaming Variables: If you want the local variable name to be different from the object key, use a colon :.

    • const { name: userName } = user; — This extracts the name property but stores it in a variable called userName.
  • Default Values: You can assign a default value that will be used if the property is undefined.

    • const { role = "Guest" } = user; — If role doesn't exist, it defaults to "Guest".
  • Nested Destructuring: You can extract data from objects inside other objects by mirroring the structure.

    • const { address: { city } } = user;.
  • Rest Property: Use the spread operator (...) to collect all remaining properties into a new object.

    • const { name, ...others } = user;others will contain all properties except name.

Common Use Cases

  • Function Parameters: Destructuring directly in a function's arguments is widely used in frameworks like React to handle props.

    javascript

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

    Use code with caution.

  • Returning Multiple Values: Functions can return an object, allowing the caller to selectively extract only what they need.

  • Loops: You can destructure objects while iterating through an array of objects or using Object.entries().

Important Constraints

  • Null/Undefined Errors: Trying to destructure null or undefined will throw a TypeError.

  • Assignment Without Declaration: If you destructure into variables that are already declared, you must wrap the entire expression in parentheses.

    • ({ a, b } = { a: 1, b: 2 });.

Default values

Default values are used when a variable or function parameter is undefined.

👉 They provide a fallback value automatically.

1️⃣ Default values in functions

Example

function greet(name = "Guest") {
  console.log("Hello " + name);
}

greet();
greet("Hitakshi");

Output

Hello Guest
Hello Hitakshi

How it works

If no argument is passed:

name = "Guest"

Otherwise, passed value is used.

2️⃣ Default values in destructuring

Array destructuring

const arr = [10];

const [a, b = 20] = arr;

console.log(a);
console.log(b);

Output

10
20

Object destructuring

const user = {
  name: "Hitakshi"
};

const { name, age = 18 } = user;

console.log(name);
console.log(age);

Output

Hitakshi
18

3️⃣ Using logical OR (||) for defaults

Older approach:

let username = "";

let name = username || "Guest";

console.log(name);

⚠️ Problem:

  • Treats 0, false, "" as false too.

Better modern approach: Nullish coalescing (??)

let username = "";

let name = username ?? "Guest";

console.log(name);

👉 Only uses default if value is:

  • null

  • undefined

Visual overview

https://images.openai.com/static-rsc-4/YnknvoldKJMaQ7WGpszF7dPbwFlu5tOkQmUuk3Ac48wVy4ih39XZ8KDyFo5CFhg3phCS46fJ-q3tEZ7UJTQ8eqn-QRDmQs9CKbQ4mlw1XPbJpo1CcOSPyPho7pOi7ZxXoXT-TU3ucGsLqjALw1h_48V1N5pSarOnMJOaJW4pV9dpEBNajDxWy3etAmobsutO?purpose=fullsize https://images.openai.com/static-rsc-4/svVbEArpcKXYIppC1pqrP9eWZ4Br9JA-NMDBH2VqI_kOTmY-eTdzPBy7yQwp_KNbUOxh4p_6mprvrKPkTo6pkL6FVzA1SprkGBCArIhDVRaEBpbOkABJ99ceF-YWCIP-5Vyj3A8seD6j_Z6OOx13FJHOQrFzRn-8J8AuUc0xs9CyAF84OQ3jjQqJSQdX0Qxi?purpose=fullsize https://images.openai.com/static-rsc-4/8Xk9s6dyN7Xj-KQrLWpencB5qqGMOg6WvnKJ7JOQyMtUyn-RfN50OJShhJFTrS0AqoDO3R-L-0G9l9_xZJ8XnR_j8Q9eZSpG1FC28ur9LgUBGekK8Zx2LgFReTQ3TmivSi_QZUIPuL5qyLdcqCm1_eT0tcLMIC44Z_Lq97WowBDI2zpgUKWx1Av3z8Qd3GHu?purpose=fullsize

Real-world uses

  • Optional function parameters

  • API response handling

  • Form defaults

  • React props

Benefits of destructuring

Destructuring is a powerful syntax introduced in ES6 that allows you to "unpack" values from arrays or properties from objects into distinct variables in a single statement.

The primary benefits of using destructuring in your JavaScript code include:

1. Cleaner and More Concise Code

  • Reduces Boilerplate: You can extract multiple properties in one line instead of writing multiple repetitive assignment statements.

  • Eliminates Dot Notation Overuse: Instead of repeatedly typing user.address.city, you can destructure city once and use it directly.

2. Improved Readability and Maintainability

  • Explicit Intent: Destructuring at the top of a function or block clearly signals to other developers which specific pieces of data will be used.

  • Self-Documenting: Variable names often mirror the data structure, making the flow of information easier to follow at a glance.

3. Enhanced Functionality

  • Default Values: You can assign fallback values during the destructuring process, preventing "undefined" bugs when a property is missing.

  • Simulated Multiple Return Values: Since JavaScript functions can only return one value, you can return an object or array and destructure it to effectively receive multiple results.

  • Cleaner Function Parameters: Destructuring directly in a function's parameter list makes the function signature explicit about what properties it expects from an object argument.

4. Powerful Data Manipulation

  • Easy Variable Swapping: You can swap the values of two variables without needing a temporary third variable (e.g., [a, b] = [b, a]).

  • Deep Extraction: Destructuring can easily pull values from deeply nested objects or arrays in a single step.

  • Aliasing: You can rename properties during extraction to avoid naming conflicts or to use more descriptive local names.

5. Safer and Modern Patterns

  • Immutable Operations: When combined with the rest operator (...), destructuring allows you to create new objects while excluding certain properties, which is essential for immutable state management in React.

  • Predictability: It ensures that the original data structure remains unmodified, making your code safer and more reliable.