Skip to main content
JavaScript Basics
CHAPTER 21 Beginner

JavaScript Destructuring and Spread Operator

Updated: May 12, 2026
20 min read

# JavaScript Destructuring and Spread Operator

As you build more complex applications, you will constantly be pulling data out of Arrays and Objects to use in your UI. Doing this one variable at a time is tedious and leads to ugly code.

In this chapter, we will learn two of the most loved features in modern JavaScript: Destructuring and the Spread Operator.

1. Introduction

Destructuring is a special syntax that allows us to "unpack" values from arrays, or properties from objects, into distinct variables in a single line of code.

The Spread Operator (...) allows us to quickly copy all or part of an existing array or object into another array or object. It's essentially a copy-paste tool built directly into the language.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Destructure objects into variables.
  • Give destructured variables new names and default values.
  • Destructure arrays into variables.
  • Use the Spread operator (...) to combine arrays and objects.
  • Use the Rest operator (...) in function parameters.
  • Build a User Settings Manager mini-project.

3. Object Destructuring

Object destructuring uses curly braces {} on the left side of the equals sign. The names of the variables you create MUST match the keys inside the object.

javascript
1234567
// Example JavaScript
const person = { name: "Alice", age: 25, city: "Paris" };

// Destructuring
const { name, age, city } = person;

console.log(name); // Output: Alice

4. Array Destructuring

Array destructuring uses square brackets [] on the left side of the equals sign. The names can be anything you want, but the order matters. The first variable gets the first item in the array.

javascript
1234567
// Example JavaScript
const colors = ["Red", "Blue", "Green"];

// Destructuring
const [primary, secondary, tertiary] = colors;

console.log(primary); // Output: Red

---

5. Real-world Examples & Code Snippets

Example 1: Object Destructuring vs Old Way

javascript
12345678910
// Example JavaScript
const user = { id: 99, role: "Admin", active: true };

// OLD WAY
// const id = user.id;
// const role = user.role;

// MODERN WAY
const { id, role } = user;
console.log(`User ${id} is an ${role}`);

Example 2: Renaming Destructured Variables

If you already have a variable named role, you can rename the destructured property using a colon :.

javascript
1234567
// Example JavaScript
const employee = { role: "Manager" };

// Extract 'role' but save it as a variable named 'jobTitle'
const { role: jobTitle } = employee;

console.log(jobTitle); // Output: Manager

Example 3: Default Values in Destructuring

If the object is missing a property, you can provide a fallback default value using =.

javascript
123456
// Example JavaScript
const settings = { theme: "Dark" }; // Missing 'notifications'

const { theme, notifications = true } = settings;

console.log(notifications); // Output: true (Default applied)

Example 4: Skipping Items in Array Destructuring

You can skip items in an array by just leaving a comma empty.

javascript
1234567
// Example JavaScript
const scores = [100, 90, 80, 70];

const [firstPlace, , thirdPlace] = scores; // Notice the double comma

console.log(firstPlace);  // Output: 100
console.log(thirdPlace);  // Output: 80

Example 5: Destructuring inside Function Parameters

This is extremely common in modern libraries like React. Instead of passing the whole object, you destructure it right in the parameters!

javascript
123456789
// Example JavaScript
const user = { name: "David", age: 40 };

// We instantly unpack name and age here
function printUser( { name, age } ) {
    console.log(`${name} is ${age} years old.`);
}

printUser(user);

Example 6: The Spread Operator (...) with Arrays

The spread operator takes an array and "spreads" its elements out. It is the best way to merge arrays.

javascript
12345678
// Example JavaScript
const group1 = ["Alice", "Bob"];
const group2 = ["Charlie", "David"];

// Merge them
const allUsers = [...group1, ...group2];

console.log(allUsers); // Output: ["Alice", "Bob", "Charlie", "David"]

Example 7: Copying an Array with Spread

Before ES6, copying an array was notoriously tricky because of memory reference bugs. Spread makes it safe and easy.

javascript
12345678
// Example JavaScript
const original = [1, 2, 3];
const safeCopy = [...original];

safeCopy.push(4); // Only updates the copy

console.log(original); // [1, 2, 3]
console.log(safeCopy); // [1, 2, 3, 4]

Example 8: The Spread Operator (...) with Objects

You can spread the properties of one object into another object.

javascript
123456789
// Example JavaScript
const basicInfo = { name: "Eve", email: "eve@test.com" };
const workInfo = { role: "Dev", salary: 80000 };

// Merge objects
const completeProfile = { ...basicInfo, ...workInfo, active: true };

console.log(completeProfile);
// Output: { name: 'Eve', email: 'eve@...', role: 'Dev', salary: 80000, active: true }

Example 9: Overriding Object Properties with Spread

If two objects have the same key, the one spread *last* wins.

javascript
12345678
// Example JavaScript
const defaultSettings = { volume: 50, theme: "light" };
const userSettings = { theme: "dark" }; // User wants dark mode

// The userSettings will overwrite the default theme
const finalConfig = { ...defaultSettings, ...userSettings };

console.log(finalConfig); // Output: { volume: 50, theme: 'dark' }

Example 10: The Rest Operator (...)

It looks exactly like the Spread operator, but it does the exact opposite. While Spread *unpacks* elements, Rest *packs* multiple elements into an array. It is heavily used in function parameters to allow an infinite number of arguments.

javascript
1234567891011
// Example JavaScript
// ...numbers catches every argument passed and packs it into an array
function addAllNumbers(...numbers) {
    let total = 0;
    for (let num of numbers) {
        total += num;
    }
    return total;
}

console.log(addAllNumbers(5, 10, 15, 20)); // Output: 50

---

6. Common Mistakes for Beginners

  1. 1. Using array brackets for objects: const [name] = {name: "John"} will throw an error. Destructuring syntax must match the data type. {} for Objects, [] for Arrays.
  1. 2. Order confusion in arrays: const [second, first] = ["Apple", "Banana"]; The variable second will hold "Apple" because it is listed first. Array destructuring relies purely on position, not names.
  1. 3. Rest vs Spread confusion: They look the same (...). Rule of thumb: If it's used in a function *definition* parameter, it's Rest. If it's used in an array/object *literal* or a function *call*, it's Spread.

7. Best Practices

  • Always use destructuring when pulling multiple values out of the same object to keep your code DRY (Don't Repeat Yourself).
  • Use the Spread operator ... whenever you need to duplicate an array or merge two objects. Avoid old methods like Object.assign() or array.concat().

8. Mini Project: User Settings Manager

Let's build a script that merges default app settings with custom user settings using Spread, and displays them using Destructuring.

HTML:

html
1234567891011121314151617181920212223242526
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: Arial; padding: 20px;}
        .dash { background: #eee; padding: 20px; border-radius: 8px; width: 300px; }
        .config-box { background: white; padding: 15px; border-radius: 5px; margin-top: 15px; }
        button { background: #007bff; color: white; border: none; padding: 10px; cursor: pointer;}
    </style>
</head>
<body>

    <div class="dash">
        <h3>App Configuration</h3>
        <button onclick="applyUserSettings()">Apply Dark Theme (User Config)</button>
        
        <div class="config-box" id="output">
            <p>Loading configuration...</p>
        </div>
    </div>

    <script src="settings.js"></script>
</body>
</html>

settings.js:

javascript
12345678910111213141516171819202122232425262728293031323334353637
// Example JavaScript

// 1. Define Default Settings
const defaultSystemConfig = {
    theme: "Light",
    notificationsEnabled: true,
    volume: 80,
    language: "English"
};

// 2. Define User Settings (User only changed the theme and volume)
const myUserSettings = {
    theme: "Dark",
    volume: 30
};

function applyUserSettings() {
    // 3. Merge them using Spread (User settings overwrite defaults)
    const finalConfig = { ...defaultSystemConfig, ...myUserSettings };
    
    // 4. Destructure the final config for easy access
    const { theme, notificationsEnabled, volume, language } = finalConfig;
    
    // 5. Output using Template Literals
    document.getElementById("output").innerHTML = `
        <strong>Theme:</strong> ${theme} <br>
        <strong>Notifications:</strong> ${notificationsEnabled ? "ON" : "OFF"} <br>
        <strong>Volume:</strong> ${volume}% <br>
        <strong>Lang:</strong> ${language}
    `;
    
    // Quick UI update to match theme
    if (theme === "Dark") {
        document.body.style.background = "#222";
        document.body.style.color = "#fff";
    }
}

9. Exercises

  1. 1. Given const user = { email: "a@a.com", id: 5 }, write a single line of destructuring code to extract both properties into variables.
  1. 2. Given const arr1 = [1, 2] and const arr2 = [3, 4], write a single line of code using the Spread operator to combine them into a variable named combined.
  1. 3. Try to destructure a property username from an empty object {} and give it a default value of "Guest".

10. MCQs (Multiple Choice Questions)

Q1: What syntax is used to destructure an object? A) const [a, b] = obj; B) const {a, b} = obj; C) const (a, b) = obj; D) const <a, b> = obj; *Answer: B*

Q2: What will be the value of x? const [x, y] = [10, 20]; A) 10 B) 20 C) [10, 20] D) undefined *Answer: A*

Q3: Which operator is represented by three dots ... ? A) The Splice Operator B) The Expand Operator C) The Spread/Rest Operator D) The Join Operator *Answer: C*

11. Interview Questions

Q: Explain how Array destructuring is different from Object destructuring. *A: Object destructuring relies on the exact property names (keys) existing in the object, regardless of order. Array destructuring relies entirely on the numerical index (order) of the elements, and you can name the resulting variables whatever you want.*

Q: Is the copy created by the Spread Operator a Deep Copy or a Shallow Copy? *A: It is a Shallow Copy. It perfectly copies primitive values (strings, numbers) at the top level. However, if the array or object contains nested objects/arrays inside it, those nested items are still passed by memory reference.*

12. FAQs

Q: Why do I see ...props in React code all the time? *A: React relies heavily on passing data objects (called props) between components. Developers use the Spread operator <Component {...props} /> to pass all properties of an object to a child component instantly without typing them out one by one.*

13. Summary

  • Destructuring cleanly extracts data into variables.
  • { key } = object for objects (must match key name).
  • [ var1, var2 ] = array for arrays (based on order).
  • Spread ... unpacks arrays/objects to copy or merge them.
  • Rest ... packs multiple function arguments into an array.

14. Next Chapter Recommendation

You now know how to manipulate objects brilliantly. But how do we actually create *blueprints* for objects, so we can generate 100 User objects that all share the same structure and methods? In the next chapter, JavaScript Classes and OOP, we will dive into Object-Oriented Programming.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·