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;
JavaScriptIn 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
JavaScriptIn 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)
JavaScriptIn 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.