Object destructuring in JavaScript

author
1
1 minute, 6 seconds Read

In JavaScript, object destructuring is a convenient feature that allows you to extract properties from objects and assign them to variables in a more concise and readable way

const { property1, property2, ... } = object;
JavaScript

In the above syntax, property1, property2, etc. are the names of the properties you want to extract from the object. The {} curly braces indicate that we are using object destructuring.

Let’s see some examples to better understand object destructuring:

Example 1:

const person = { name: 'John', age: 30, occupation: 'Engineer' };

const { name, age } = person;

console.log(name); // Output: 'John'
console.log(age);  // Output: 30
JavaScript

In this example, we have an object called person. We use object destructuring to extract the name and age properties and assign them to separate variables with the same names.

Example 2:

const book = { title: 'JavaScript Basics', author: 'Jane Doe' };

// Default values during destructuring
const { title, pages = 100 } = book;

console.log(title); // Output: 'JavaScript Basics'
console.log(pages); // Output: 100 (default value used as 'pages' property is not present in the 'book' object)
JavaScript

In this example, we extract the title property from the book object and we also set a default value of 100 for the pages property in case it is not present in the book object.

We appreciate your support and are committed to providing you useful and informative content. We are thankful for your ongoing support
We appreciate your support and are committed to providing you useful and informative content.
We are thankful for your ongoing support
Share To:

Comments

  1. avatar
    Md Zahid says:

    Brilliant breakdown of object destructuring in JavaScript! 👏 Your post beautifully demystified this feature, showcasing its elegance in simplifying assignments and boosting code clarity. Kudos for the practical examples and pro tips – they’re game-changers. Looking forward to leveling up my JS skills with more of your content! 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *