⬅ Previous Topic
JavaScript Array MethodsNext Topic ⮕
JavaScript Iterating Over Objects⬅ Previous Topic
JavaScript Array MethodsNext Topic ⮕
JavaScript Iterating Over ObjectsDestructuring in JavaScript is a clean and expressive way to extract values from arrays or properties from objects into distinct variables. This technique can simplify your code and enhance readability, especially when dealing with structured data.
Let’s start with array destructuring. It allows unpacking values from arrays into separate variables.
const numbers = [10, 20, 30];
const [a, b, c] = numbers;
console.log(a, b, c);
10 20 30
You can skip elements by leaving blanks in the destructuring pattern.
const numbers = [1, 2, 3, 4];
const [first, , third] = numbers;
console.log(first, third);
1 3
If a value is undefined
during destructuring, a default value can be provided.
const [a = 5, b = 10] = [1];
console.log(a, b);
1 10
Destructuring shines with simple tricks like swapping variables.
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y);
2 1
Object destructuring allows extracting properties using variable names that match the property keys.
const user = { name: "Alice", age: 25 };
const { name, age } = user;
console.log(name, age);
Alice 25
You can assign a property to a variable with a different name.
const person = { firstName: "John", lastName: "Doe" };
const { firstName: f, lastName: l } = person;
console.log(f, l);
John Doe
Just like arrays, you can set default values when properties are missing.
const settings = { theme: "dark" };
const { theme, fontSize = "16px" } = settings;
console.log(theme, fontSize);
dark 16px
You can destructure nested objects too, in one line.
const profile = {
user: {
id: 101,
info: {
email: "user@example.com"
}
}
};
const { user: { info: { email } } } = profile;
console.log(email);
user@example.com
The rest operator (...
) captures the remaining items.
const [first, ...rest] = [1, 2, 3, 4];
console.log(first);
console.log(rest);
1
[2, 3, 4]
You can also use rest syntax to gather remaining properties.
const { a, ...others } = { a: 10, b: 20, c: 30 };
console.log(a);
console.log(others);
10
{ b: 20, c: 30 }
Destructuring makes your function parameters expressive and intuitive.
function greet({ name, age }) {
console.log(`Hello, ${name}. You are ${age} years old.`);
}
const person = { name: "Emma", age: 28 };
greet(person);
Hello, Emma. You are 28 years old.
Destructuring is also powerful in loops for unpacking values cleanly.
const users = [
{ id: 1, username: "user1" },
{ id: 2, username: "user2" }
];
for (const { id, username } of users) {
console.log(`${id}: ${username}`);
}
1: user1
2: user2
⬅ Previous Topic
JavaScript Array MethodsNext Topic ⮕
JavaScript Iterating Over ObjectsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.