Preview:
// Example object
const person = {
    name: "Alice",
    age: 25,
    location: {
        city: "Wonderland",
        country: "Fantasy"
    }
};

// Destructuring the object
const { name, age } = person;

console.log("Name:", name); // Output: "Name: Alice"
console.log("Age:", age);   // Output: "Age: 25"

// Destructuring nested objects
const { city, country } = person.location;

console.log("City:", city);     // Output: "City: Wonderland"
console.log("Country:", country); // Output: "Country: Fantasy"

// Assigning to new variable names
const { name: fullName, age: years } = person;
console.log("Full Name:", fullName); // Output: "Full Name: Alice"
console.log("Years:", years);         // Output: "Years: 25"

// Rest parameter in object destructuring
const { name: personName, ...restOfPerson } = person;
console.log("Person Name:", personName); // Output: "Person Name: Alice"
console.log("Rest of Person:", restOfPerson); // Output: "Rest of Person: { age: 25, location: { city: 'Wonderland', country: 'Fantasy' } }"
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter