0% found this document useful (0 votes)
4 views8 pages

De Structuring

Destructuring is an ES6 feature that simplifies the extraction of values from arrays and objects, enhancing code readability and reducing repetition. It includes techniques for array and object destructuring, such as extracting values by position or key, setting default values, and renaming variables. The document also covers practical examples and exercises to illustrate the use of destructuring and arrow functions.

Uploaded by

Mohana D
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views8 pages

De Structuring

Destructuring is an ES6 feature that simplifies the extraction of values from arrays and objects, enhancing code readability and reducing repetition. It includes techniques for array and object destructuring, such as extracting values by position or key, setting default values, and renaming variables. The document also covers practical examples and exercises to illustrate the use of destructuring and arrow functions.

Uploaded by

Mohana D
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Destructuring

Destructuring is a convenient way to extract values from arrays or objects and


assign them to variables. This ES6 feature makes your code cleaner, more
readable, and reduces repetitive tasks when dealing with structured data.
Array Destructuring
a. Extracting Values by Position
Array destructuring allows you to extract elements from an array based on their
position.
Example: Basic Array Destructuring
javascript
let fruits = ["apple", "banana", "cherry"];
let [first, second] = fruits;

console.log(first); // Output: apple


console.log(second); // Output: banana
Explanation:
● The [] syntax on the left side of the assignment corresponds to the array
elements on the right.
● first gets the value of fruits[0], and second gets the value of fruits[1].

b. Default Values in Destructuring


You can set default values to avoid undefined if the array has fewer elements
than expected.
Example: Default Values
javascript
let numbers = [42];
let [a, b = 10] = numbers;

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.

c. Demo: Swap Variables Using Array Destructuring


Array destructuring can be used to swap two variable values without a
temporary variable.
Example: Swapping Variables
javascript
let x = 1, y = 2;
[x, y] = [y, x];

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;

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


console.log(age); // Output: 25
Explanation:
● The {} syntax on the left side matches the keys in the object.
● Variables name and age get their values from person.name and
person.age.

b. Renaming Variables During Destructuring


You can assign object properties to variables with different names.
Example: Renaming Variables
javascript
let person = { name: "Bob", age: 30 };
let { name: fullName, age: years } = person;

console.log(fullName); // Output: Bob


console.log(years); // Output: 30
Explanation:
● name: fullName assigns the name property to the variable fullName.
● age: years assigns the age property to the variable years.

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;

console.log(username); // Output: john_doe


console.log(email); // Output: [email protected]
Explanation:
● The profile property is an object, so { username, email } destructures its
keys.
● You can directly access username and email without referencing profile.

Demo: Extract Data from a Nested Object


Let’s combine these concepts in a practical example.
Scenario: Extract data about a product from a nested object.
Code Example:
javascript
let product = {
id: 101,
name: "Laptop",
specs: {
processor: "Intel i7",
memory: "16GB",
},
};

let {
name: productName,
specs: { processor, memory },
} = product;

console.log(productName); // Output: Laptop


console.log(processor); // Output: Intel i7
console.log(memory); // Output: 16GB
Explanation:
● name: productName assigns the product name to productName.
● specs: { processor, memory } extracts the processor and memory
properties from the nested specs object.

Exercise 1: Convert a Regular Function to an Arrow Function


Task: Convert a regular function to an arrow function and compare the
behavior of this.
Step-by-Step Explanation:
1. Regular Function Behavior:
o In regular functions, the value of this depends on how the function
is called.
o When used as a method, this refers to the object calling the
method.
o In standalone calls, this might refer to the global object or
undefined in strict mode.
2. Arrow Function Behavior:
o Arrow functions inherit this from the surrounding lexical scope.
o They do not bind their own this, so this remains consistent
regardless of how they are called.

Code Example:
Regular Function:
javascript
const obj = {
name: "Alice",
greet: function () {
console.log(`Hello, my name is ${this.name}.`); // `this` refers to
obj
},
};

obj.greet(); // Output: Hello, my name is Alice.


Arrow Function:
javascript
const objArrow = {
name: "Alice",
greet: () => {
console.log(`Hello, my name is ${this.name}.`); // `this` does
NOT refer to obj
},
};

objArrow.greet(); // Output: Hello, my name is undefined.


Explanation:
● Why the difference? In the arrow function example, this inherits from
the parent scope, which is typically the global scope. Since this.name
doesn't exist globally, it becomes undefined.
● Takeaway: Use regular functions for object methods when you want this
to refer to the object. Use arrow functions for functions that do not
require their own this.
Exercise 2: Destructure an Object and Use Template Literals
Task: Write a function that accepts an object with properties name, age, and
city. Use destructuring to extract the properties and print them in a formatted
string using template literals.
Step-by-Step Explanation:
1. Destructure Object Properties:
o Extract values directly from the object using {}.
o Rename variables during destructuring if necessary.
2. Use Template Literals:
o Format the extracted values into a readable string using ${}.
Code Example:
javascript
function printPersonDetails(person) {
// Destructuring the properties
const { name, age, city } = person;

// Using template literals to format the output


console.log(`Name: ${name}, Age: ${age}, City: ${city}`);
}

// 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;

console.log(`Name: ${name}, Age: ${age}, City: ${city}`);


}

// Object with missing properties


const incompletePerson = { name: "Charlie" };

// 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.

You might also like