🌱BeginnerModern JavaScript (ES6+)
Destructuring
Unpacking values from arrays and objects into named variables in one line.
Overview
Destructuring is a syntax for extracting values from arrays and objects into separate variables. Instead of writing const name = user.name; const age = user.age; you write const { name, age } = user; a single line that reads clearly and is much harder to typo.
Array destructuring uses position: const [first, second] = array pulls the first and second elements. Object destructuring uses keys: const { name, age } = obj pulls the name and age properties. Both support default values, renaming, and nested patterns.
Destructuring is used constantly in modern JavaScript: in function parameters, for loop variables, when working with API responses, and when importing from modules. Mastering it makes code dramatically shorter and more readable.
Key Points
- •Array destructuring: const [a, b] = [1, 2] position-based
- •Object destructuring: const { x, y } = obj key-based
- •Rename on destructure: const { name: firstName } = user
- •Default values: const { role = "user" } = obj used when the property is undefined
- •Skip elements in arrays: const [, second, , fourth] = arr
- •Rest in destructuring: const { a, ...rest } = obj pulls a out, rest gets everything else
Examples
Array and object destructuring basics
// Array destructuring
const [x, y, z] = [10, 20, 30];
console.log(x, y, z); // 10 20 30
// Object destructuring
const user = { name: "Alice", age: 30, city: "Paris" };
const { name, age } = user;
console.log(name, age); // Alice 30Renaming and defaults
const config = { host: "localhost", port: 5432 };
// Rename: host → hostname, default for timeout
const { host: hostname, port, timeout = 30 } = config;
console.log(hostname); // "localhost"
console.log(timeout); // 30 (default, not in config)Destructuring function parameters very common
function displayUser({ name, age, role = "user" }) {
console.log(`${name}, age ${age}, role: ${role}`);
}
displayUser({ name: "Bob", age: 25 });
// Bob, age 25, role: user
displayUser({ name: "Admin", age: 40, role: "admin" });
// Admin, age 40, role: adminDestructuring in parameters avoids tedious obj.name, obj.age inside the function body.
Common Mistakes
- Confusing the rename syntax: { name: firstName } destructures name and calls it firstName locally not { firstName: name }
- Trying to destructure null or undefined always ensure the value exists first
- Forgetting that array destructuring is position-based: const [a, b] = [1, 2] is fine, but skipping elements requires commas: const [, second] = [1, 2]
Note
Destructure in function parameters for any function that takes an options object it documents exactly which properties the function uses and provides defaults in one place.
Exercises
Write JavaScript code to solve each exercise. Run it and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4