// Array Destructuring Example
const fruits = ["Apple", "Banana", "Cherry"];
const [firstFruit, secondFruit] = fruits;
console.log("First Fruit:", firstFruit); // Output: Apple
console.log("Second Fruit:", secondFruit); // Output: Banana
// Skipping Elements Example
const numbers = [1, 2, 3, 4, 5];
const [one, , three] = numbers;
console.log("One:", one); // Output: 1
console.log("Three:", three); // Output: 3
// Rest Parameter Example
const colors = ["Red", "Green", "Blue", "Yellow"];
const [primaryColor, ...otherColors] = colors;
console.log("Primary Color:", primaryColor); // Output: Red
console.log("Other Colors:", otherColors); // Output: ["Green", "Blue", "Yellow"]
// Function Returning Array Example
function getCoordinates() {
return [10, 20];
}
const [x, y] = getCoordinates();
console.log("X Coordinate:", x); // Output: 10
console.log("Y Coordinate:", y); // Output: 20
// Object Destructuring Example
const person = {
name: "John",
age: 30,
city: "New York"
};
const { name, age } = person;
console.log("Name:", name); // Output: John
console.log("Age:", age); // Output: 30
// Renaming Variables Example
const { name: fullName, age: years } = person;
console.log("Full Name:", fullName); // Output: John
console.log("Years:", years); // Output: 30
// Default Values Example
const { country = "USA" } = person;
console.log("Country:", country); // Output: USA (default value)
// Nested Destructuring Example
const user = {
id: 1,
details: {
name: "Alice",
age: 25,
address: {
city: "Los Angeles",
zipCode: "90001"
}
}
};
const { details: { name:userName, address:{ city:userCity } } } = user;
console.log("User Name:", userName); // Output: Alice
console.log("User City:", userCity); // Output: Los Angeles
Comments