De Structuring
De Structuring
console.log(a); // Output: 42
console.log(b); // Output: 10 (default value)
Explanation:
● The b variable gets a default value of 10 because the array has no second
element.
console.log(x); // Output: 2
console.log(y); // Output: 1
Explanation:
● [x, y] = [y, x] reassigns x to y's value and y to x's value in one step.
● No need for a temporary variable, making the code concise and elegant.
Object Destructuring
a. Extracting Values by Key
Object destructuring allows you to extract properties from an object into
variables with the same name.
Example: Basic Object Destructuring
javascript
let person = { name: "Alice", age: 25, city: "Wonderland" };
let { name, age } = person;
c. Nested Destructuring
You can extract values from nested objects using destructuring.
Example: Nested Object Destructuring
javascript
let user = {
id: 1,
profile: {
username: "john_doe",
email: "[email protected]",
},
};
let {
profile: { username, email },
} = user;
let {
name: productName,
specs: { processor, memory },
} = product;
Code Example:
Regular Function:
javascript
const obj = {
name: "Alice",
greet: function () {
console.log(`Hello, my name is ${this.name}.`); // `this` refers to
obj
},
};
// Example object
const person = { name: "Bob", age: 30, city: "Wonderland" };
// Function call
printPersonDetails(person);
// Output: Name: Bob, Age: 30, City: Wonderland
Enhanced Example: Handling Missing Values with Default Destructuring:
javascript
function printPersonDetailsWithDefaults(person) {
// Destructuring with default values
const { name = "Unknown", age = "Not specified", city =
"Unknown" } = person;
// Function call
printPersonDetailsWithDefaults(incompletePerson);
// Output: Name: Charlie, Age: Not specified, City: Unknown
Explanation:
● Why use destructuring? It simplifies extracting values from objects,
making your code cleaner and easier to read.
● Why use template literals? They make string concatenation more
readable and intuitive, especially when dealing with dynamic values.