Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Destructuring in JavaScript

Posted on Sep 22 • Originally published at honeybadger.io This article was originally written by Adebayo Adams on the Honeybadger Developer Blog.When building software with JavaScript, arrays and objects are the first options that come to mind when declaring related or groups of values in your code because they are arguably the most flexible data types in JavaScript. However, although the objects or arrays often contain related values, you rarely need the whole Object or array at once; you only use a part of the object or arrays at a time. Digging deep into the array or object to get the necessary value or properties can be very frustrating.In this article, you will learn about destructuring in JavaScript, the benefits of destructuring, how to destructure arrays and objects, and how to use it for easier data access in your applications. You will also learn about mixed destructuring, the spread operator in JavaScript, and how to destructure parameters.Note: Destructure is an English word that means to destroy the structure of something.Next, let's look at what you need to get the most out of this article.To follow this tutorial, you only need to have a basic understanding of JavaScript. Knowledge of variables, arrays, objects, functions, and parameters would be beneficial.Now that you know what you need to follow along, I’ll briefly introduce the concepts of arrays and objects in JavaScript in the next section.As mentioned above, destructuring mainly works for objects and arrays, so I'll briefly describe those in this section.An array in JavaScript is a collection of elements a numerical index can access. The elements in an array can be of any data type, including numbers, strings, and even other arrays or objects.Arrays are created using square brackets, and individual elements can be accessed using their index, which starts at 0. Below is an example of how to create an array in JavaScript:The code above creates an array called arr that contains four elements (i.e., the numbers 1 and 3 and the strings two and four) and then logs the second value in the array, which is the index 1 to the console. You can read more about JavaScript arrays hereNext, let's look at objects in the next section.Objects in JavaScript are collections of key-value pairs. The keys in an object are strings, while the values can be of any data type. Objects are created using curly braces, and individual properties can be accessed using dot notation or square brackets. Here is an example of creating an object in JavaScript:The code above creates an object called obj that has three properties: name, age, and hobbies. The value of the name property is a string, "John Doe", the value of the age property is a number, 30, and the value of the hobbies property is an array.The code then logs the name property using the dot notation, which returns "John Doe". You can read more about JavaScript objects hereNow that you know what arrays and objects are in JavaScript, let's look at what destructuring is in JavaScript.Destructuring in JavaScript is dissecting data structures, arrays, and objects, in this case, to easily access the values inside them. Destructuring helps to unpack values from arrays and objects into distinct variables, so you do not have to dig through large arrays or objects to get the values you need.JavaScript allows you to destructure arrays, objects, and function parameters. In the next section, let's look at how to destructure arrays in JavaScript.In this section, I will show you how to use array destructuring in JavaScript.The basic syntax for array destructuring uses square brackets on the left-hand side of an assignment statement and the array on the right-hand side. For example, to extract the first element of an array and assign it to a variable, you can use the following code:The code above creates an array called numbers that contains five numbers and then extracts the first number in the array and assigns it to a variable called firstNumber. Finally, the code logs firstNumber in the console, which should return 1.You can also extract multiple elements from an array and assign them to multiple variables:The code above extracts the first three elements of the array and assigns them to the variables firstNumber, secondNumber, and thirdNumber, respectively, and logs them to the console:You can also use destructuring to extract elements from nested arrays:The example above creates a nestedArrs array, extracts the first three elements of the nested array, and logs them to the console:Let's look at how to destructure objects in the next section.JavaScript allows you to extract properties from an object and assign them to variables. This feature is handy when working with large objects or extracting specific properties from an object. In this section, I'll show you how to use object destructuring in JavaScript.The basic syntax for object destructuring uses curly braces on the left-hand side of an assignment statement and the object on the right-hand side. For example, to extract a property called "brand" from an object and assign it to a variable, you can use the following code:The code above creates an object called car that has two properties (i.e., brand and color), uses object destructuring to extract the brand property of the object and assign it to a variable called "brand", and then logs the value to the console:You can also extract multiple properties from an object and assign them to multiple variables:The code above extracts the brand and year properties of the object and assigns them to the variables brand and year, respectively.You can also use destructuring to extract properties from nested objects:The code above creates an address object and a person object with the address nested inside it and then extracts the name, and age properties from the person object and city property from the address object and assigns them to the variables name, age, and city, respectively. It then logs them to the console:Note: You can go as deep as you want; it doesn't matter how deep the object is.Sometimes, you might need the value of an object property that might not be present in the given object. In that case, you can destructure the object and add default values for properties that might not be present in the object:The code above creates a job object that has no isRemote property and adds a default value for the isRemote property in case it is not present in the job object. In this instance, the variable isRemote is assigned the value false:In addition to default values, you can also change the name of a property using an alias:The code above will return the value of the role property correctly in the console:Note: The jobTitle in this case is called an alias, and it is added after a : in front of the actual property name. Furthermore, you will get an error if you try to console.log(role) after declaring an alias.Let's look at rest items in the next section.The rest operator (...) in JavaScript is a powerful feature that allows developers to gather the remaining items in an array or an object into a new array or object. This can be useful in various situations, such as when working with function arguments or destructuring arrays and objects.For example, if you need the first three elements from an array of books and need the remaining elements that are in the array, you can use the rest operator:The code above creates a top20Books array containing 20 books, destructured the first three books and the remaining books, and then logs the first three books to the console:The ...remainingBooks is an array that can be used like a regular array:The code above will log the remaining books in the array to the console:Now that you know how rest items work in JavaScript, let's look at mixed destructuring in the next section.Mixed destructuring is a combination of both object destructuring and array destructuring; it allows you to extract values from arrays and objects in a single destructuring assignment.For example, if you have an object with an array inside of it, you can destructure the object as well as the array with a single line:The code above creates a user object that has an address object and a hobbies object inside it and extracts name, age, city, state, and one of the hobbies using mixed destructuring. You can now use the values that you extracted:The code above will log something like this to the console:Now that you know how to use mixed destructuring, let's look at how to destructure function parameters in the next section.JavaScript allows you to extract values from an object or array passed as a parameter to a function. Destructuring parameters is quite straightforward, as you only need to use the destructuring syntax inside the function:You can also do the same for arrays:The code above creates an array of top10Books and a function that logs the first three books and the remaining books in the console. The result should look like this:Now that you know how to use destructuring in JavaScript, let's look at why you should consider using destructuring.Concise and readable codeOne of the main benefits of destructuring is that it allows you to write more concise and readable code. By using destructuring, you can extract values from arrays and objects in a single line of code, making it easier to understand what the code is doing. This is particularly useful when working with large data structures, as it allows you to focus on the essential parts of the data rather than getting lost in the details.Improved performanceAnother benefit of destructuring is that it can improve the performance of your code. When you extract values from an array or object, you create a new variable that references the value. You can manipulate the value without affecting the original data structure. This can be particularly useful when working with large data sets, as it allows you to work with a smaller subset of the data, which can be more efficient.Better handling of default valuesDestructuring also allows you to set default values for variables. If the value you are trying to extract from an array or object is not present, the default value will be used instead. This is particularly useful when working with data that may be incomplete or missing specific values. By setting default values, you can ensure that your code will still work correctly even if the data is incomplete.Easier handling of nested propertiesAnother benefit of destructuring is that it quickly extracts nested properties from an object. With destructuring, you can extract values with a single line of code, making it much easier to work with nested properties.Better handling of function parametersFinally, destructuring can also be used to extract values from function parameters. This allows you to easily extract specific values from an object or array passed as a parameter to a function. This can be particularly useful when working with complex data structures, as it allows you to focus on the specific values you need without navigating through the entire data structure.Thanks for reading! Hopefully, this article achieved its aim of teaching you everything you need to know about destructuring in JavaScript. You’ve learned how to destructure arrays, objects, and function parameters, as well as how to destructure a mixed data structure.Templates let you quickly answer FAQs or store snippets for re-use.At risk of splitting hairs... let [firstBook, secondBook, thirdBook, ...remainingBooks] = top20BooksThis is an example of a SPREAD operator, not a REST operator. And while the operator is exactly the same in Javascript ... for both spread and rest, the usage is different.Rest operators are typically used in method parameters to gather all the remaining arguments into a single array variable.Put another way: Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Cample.js - Sep 19 Programming with Shahan - Sep 22 Ilir Beqiri - Sep 21 Kristijan Pajtasev - Sep 21 Zero-instrumentation, 360 degree coverage of errors, outages and service degradation. Deploy with confidence and be your team's devops hero. Once suspended, honeybadger will not be able to comment or publish posts until their suspension is removed. Once unsuspended, honeybadger will be able to comment and publish posts again. Once unpublished, all posts by honeybadger will become hidden and only accessible to themselves. If honeybadger is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to Honeybadger Staff. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag honeybadger: honeybadger consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging honeybadger will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Destructuring in JavaScript

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×