Extract Named or Positioned Values
Extract Named or Positioned Values
Destructuring binds values from an object's properties or an array's positions. A default applies when the extracted value is undefined, allowing an absent mark to be handled explicitly.
Before this topic, review Transform, Select and Summarize if its terms are unfamiliar.
What you’ll learn
- Explain extract named or positioned values through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The supplied mark is defined, so the default is not used.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
const { name, marks = 0 } = { name: "Diya" };
console.log(name);
console.log(marks);
Expected output
Diya
0Run in JavaScript compiler →Destructuring Assignment
Destructuring 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.
Why Use Destructuring?
- Simplifies variable assignment from objects and arrays.
- Reduces repetitive code when accessing object properties or array elements.
- Improves clarity in function parameters and return values.
Destructuring Arrays
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
Skipping Elements
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
Default Values
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
Swapping Variables
Destructuring shines with simple tricks like swapping variables.
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y);
2 1
Destructuring Objects
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
Renaming Variables
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
Default Values in Object Destructuring
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
Nested Object Destructuring
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
Rest Operator with Arrays
The rest operator (...) captures the remaining items.
const [first, ...rest] = [1, 2, 3, 4];
console.log(first);
console.log(rest);
1
[2, 3, 4]
Rest Operator with Objects
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 in Function Parameters
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.
Using Destructuring in Loops
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
Recognize the important boundary
A default does not replace null. Destructuring an absent object itself fails unless you provide an appropriate fallback.
Try a small variation
JavaScript · original source for practice
const { name, marks = 0 } = { name: "Diya" };
console.log(name);
console.log(marks);
Your task: Replace {name:'Diya'} with {name:'Diya', marks:72}. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The supplied mark is defined, so the default is not used.
JavaScript · complete worked variation
const { name, marks = 0 } = { name: "Diya", marks: 72 };
console.log(name);
console.log(marks);
Expected output
Diya
72Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
const { name, marks = 0 } = { name: "Diya" };
console.log(name);
console.log(marks);
Keep the useful idea
Destructuring binds values from an object's properties or an array's positions. A default applies when the extracted value is undefined, allowing an absent mark to be handled explicitly.
Check your variation against this explanation: The supplied mark is defined, so the default is not used.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.