Javascript Object Destructuring Explained with Examples

Object destructuring is a feature in Javascript that allows you to extract values from objects and assign them to variables in a more concise and readable way.

This feature was introduced in ES6 and has since become a popular technique among Javascript developers.

In order to use object destructuring, you can use curly braces {} to specify the properties you want to extract from an object. Let’s take a look at some examples of how this incredible feature can be used:

1. The basic Object Destructuring

const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name); // Output: John
console.log(age); // Output: 30

Here we declare a person object with name and age properties. We then use destructuring to extract these properties and assign them to variables with the same names. We can then use them to access the values of the properties.

2. Renaming variables

const person = { name: 'John', age: 30 };
const { name: fullName, age: years } = person;
console.log(fullName); // Output: John
console.log(years); // Output: 30

Here we use destructuring to extract the name and age properties from the person object. However, we also use the colon : syntax to rename the variables to fullName and years. This allows us to use different variable names while still extracting the values we need.

3. Default values

const person = { name: 'John' };
const { name, age = 30 } = person;
console.log(name); // Output: John
console.log(age); // Output: 30

Here we use destructuring to extract the name property from the person object. We also declare a default value of 30 for the age variable in case it is not defined in the person object. This ensures that our code does not throw an error if the age property is missing.

4. Dynamic property names

const helloStr = "Hello world!"
const { length, [length-1]: last } = str
console.log(length)  // 12
console.log(last)  // "!"

Here we use destructuring to dynamically assing last as the new property name from the helloStr variable in order to get the last character from the string.

Final Thoughts

Object Destructuring is a powerful feature that will not only make you look cool but also will help you to write cleaner and more efficient code that will be easier to maintain and understand.

Ready for more Javscript learning? Check out this 👉 Ways to Title Case Strings with Javascript