Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (158).NET Core  (28).NET MAUI  (50)Angular  (67)ASP.NET  (50)ASP.NET Core  (78)ASP.NET MVC  (88)Azure  (32)Blazor  (144)DocIO  (23)Essential JS 2  (80)Essential Studio  (171)File Formats  (28)Flutter  (121)JavaScript  (179)Microsoft  (112)PDF  (67)React  (55)Succinctly series  (126)Syncfusion  (582)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (36)Webinar  (32)Windows Forms  (58)WinUI  (45)WPF  (135)Xamarin  (153)XlsIO  (25)Other CategoriesBarcode  (5)BI  (29)Bold BI  (4)Build conference  (6)Business intelligence  (53)Button  (4)C#  (118)Chart  (56)Cloud  (11)Company  (445)Dashboard  (7)Data Science  (3)Data Validation  (6)DataGrid  (54)Development  (372)Doc  (7)DockingManager  (1)eBook  (95)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (23)Extensions  (17)File Manager  (4)Gantt  (11)Gauge  (9)Git  (4)Grid  (27)HTML  (10)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (298)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (29)Performance  (9)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (7)Road Map  (10)Scheduler  (36)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (22)Solution Services  (2)Spreadsheet  (11)SQL  (8)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (91)UI  (209)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (23)Visual Studio Code  (14)Web  (341)What's new  (194)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
Top 7 JavaScript Object Destructuring Techniques

Top 7 JavaScript Object Destructuring Techniques

JavaScript object destructuring was introduced with the ES6 update to help developers extract multiple properties from objects at once. This was revolutionary since objects are widely used in JavaScript as a complex data structure.

There are multiple object destructuring techniques available in JavaScript. As developers, we must understand these techniques to write clean code and improve our efficiency.

This article will discuss the top seven JavaScript object destructuring techniques to give you a better understanding of how and when they should be used.

What is JavaScript object destructuring?

Object destructuring is the process of extracting multiple properties or items from objects at once. This technique is really useful when accessing object properties in JavaScript.

For example, suppose you have an object named article with multiple properties like in the following code example:

let article = { 
  id: '001', 
  title: 'JavaScript Object Destructuring', 
  writer: 'Chameera'
};

Without object restructuring, you will have to extract the properties like this:

let id = article.id; 
let title = article.title;
let writer = article.writer;

However, if you use object destructuring, you can extract all the properties with a single line of code:

let { id, title, writer } = article;

console.log(id); // 001
console.log(title); // JavaScript Object Destructuring
console.log(writer); // Chameera

Here, the object properties are assigned to articleId, articleName, and writerName, respectively. If the variables have the same name as the object properties, you can write the code more concisely as follows:

let { id, title, writer } = article;

console.log(id); // 001
console.log(title); // JavaScript Object Destructuring
console.log(writer); // Chameera

We have seen how JavaScript object destructuring works, so let’s discuss different techniques we can use.

1. Nested object destructuring

As developers, we often have to deal with nested objects. With the traditional approach, we have to follow the dot notation to access the nested properties.

let article = { 
  id: '001', 
  title: 'JavaScript Object Destructuring', 
  writer: {
    name: 'Chameera'
  }
};

console.log(article.writer.name) // Chameera

However, object destructuring allows you to extract nested properties without using multiple destructuring assignments directly.

let article = { 
  id: '001', 
  title: 'JavaScript Object Destructuring', 
  writer: {
    name: 'Chameera'
  }
};

let { 
  id: articleId, 
  title: articleTitle, 
  writer: { 
    name: writerName 
  } 
} = article;

console.log(articleId); // 001
console.log(articleTitle); // JavaScript Object Destructuring
console.log(writerName); // Chameera

2. Destructuring function arguments

There are scenarios where we pass objects into functions and access the properties of those functions using dot notation like this:

let article = { 
  title: 'JavaScript Object Destructuring',
  writer: 'Chameera'
};

let displayDetails = (article) = > {
  console.log(article.title); // JavaScript Object Destructuringconsole.log(article.writer); // Chameera
};

displayDetails(article);

With object destructuring, we can extract the object properties from the function signature.

let article = { 
  title: 'JavaScript Object Destructuring',
  writer: 'Chameera'
};

let displayDetails = ({title, writer}) = > {
  console.log(title); // JavaScript Object Destructuring
  console.log(writer); // Chameera
};

displayDetails(article);

3. Destructuring with default values

Sometimes, the same types of objects might not have the exact number of properties. You can assign default values for the properties using object destructuring in such situations.

For example, suppose you are getting a list of articles from a database, and some articles do not have a subtitle. In such situations, you can assign a default value while destructuring. If the object contains a subtitle, the real value will be assigned to the variable. If not, default values will be assigned.

let article = { 
  title: 'JavaScript Object Destructuring',
  writer: 'Chameera'
};

let { title, subtitle = 'No Sub Title', writer} = article;

console.log(title); // JavaScript Object Destructuring
console.log(subtitle); // No Sub Title
console.log(writer); // Chameera

let article = { 
  title: 'JavaScript Object Destructuring',
  subtitle: 'Top 7 JavaScript Object Destructuring Techniques',
  writer: 'Chameera'
};

let { title, subtitle = 'No Sub Title' writer} = article;

console.log(title); // JavaScript Object Destructuring
console.log(subtitle); // Top 7 JavaScript Object Destructuring Techniques
console.log(writer); // Chameera

4. Destructuring null objects

In JavaScript, it is common to return objects from functions, and developers directly extract the properties of the returned object using object destructuring.

function getArticle() {
   
  let article = { 
    title: 'JavaScript Object Destructuring',
    subtitle: 'Top 7 JavaScript Object Destructuring Techniques'
  };

  return article.
}

let { title, subtitle} = getArticle();

However, there can be scenarios where the returned object is null. In such situations, we need to modify the object destructuring statement to handle null objects. If not, the application will throw a TypeError.

function getArticle() {
  return null.
}

let { title, subtitle} = getArticle(); // Type Error
let { title, subtitle} = getArticle() || {}; // No Error

5. Using the rest parameter

The rest parameter (…) allows functions to accept an indefinite number of arguments as an array.

function myFunction(a, b, ...theArgs) {
  // ...
}

We can use this rest parameter in object destructuring as well. If there are many properties in an object, we can assign the essential values to variables and unpack all the remaining values to another object using the rest parameter.

let languages = {
  language1 : 'Java', 
  language2 : 'JavaScript', 
  language3 : 'C', 
  language4 : 'Python', 
  language5 : 'C#', 
  language6 : 'C++', 
  language7 : 'Ruby'
};

let { language1, language2, ...otherLanguages } = languages;

console.log(language1); // Java
console.log(language2); // JavaScript
console.log(otherLanguages) ;
/* 
{ "language3": "C","language4" : "Python","language5": "C#","language6": "C++",
  "language7": "Ruby"
} */

6. Assigning dynamic object keys

In all the previous examples, object keys were fixed. So, can we use object destructuring if the object keys are dynamic? Yes. We can assign object keys dynamically when destructuring.

For example, suppose you have an object of users like below, and you need to extract the designation based on the username dynamically.

let users = {
  Paul: 'Software Engineer',
  Mike: 'Senior Software Engineer',
  George: 'Team Lead',
  ... 
};

In such situations, we can restructure the object using a variable as the object key to only fetch the required value.

let users = {
  Paul: 'Software Engineer',
  Mike: 'Senior Software Engineer',
  George: 'Team Lead',
  ... 
};

let userKey = 'Mike';
let { [userKey] : selectedUser } = users;

console.log(selectedUser); // Senior Software Engineer

Likewise, you can change the value of the userKey variable and fetch the user details dynamically.

7. Combined object and array destructuring

JavaScript supports both object and array destructuring. If you have an array with multiple objects inside, you can combine the power of both object and array destructuring to extract nested objects and their properties easily.

let languages = [
  { id: 1, name: 'Java' }, 
  { id: 2, name: 'JavaScript' },
  { id: 3, name: 'C' }, 
  { id: 4, name: 'Python' },
  { id: 5, name: 'C#' },
  { id: 6, name: 'C++' },
  { id: 7, name: 'Ruby' }
];

let [, , , { name }, , , ] = languages;

console.log(name) //Python

As you can see, I have used commas to skip the array objects. It is a feature in JavaScript array destructuring. You can use commas to skip elements of the array and only get the required elements.

Conclusion

In this article, I discussed seven JavaScript destructuring techniques every developer should know. However, the above list is only a subset of available object destructuring techniques.

If you haven’t used object destructuring in JavaScript before, you can start with the techniques in this article and gradually move on to others. Adopting these techniques will improve your coding skills and make your code more readable.

I hope you found this article helpful. Thank you for reading.

Syncfusion Essential JS 2 is the only suite you will ever need to build an app. It contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package. Download a free trial to evaluate the controls today.

If you have any questions or comments, you can also contact us through our support forumssupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin

Comments (1)

Awesome Article.

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top