Demystifying destructuring in JavaScript for everyone to boost productivity
BG Image — Unsplash
Destructuring is a very popular term among JavaScript developers that is most unused as well. Most people hear or learn the term while starting with JavaScript but forget to use it once they start working on real-world projects. Not saying that there are no developers who use this, but I have seen people looking like it is some complex syntax when destructuring is used in code. While a quick glance can make it look like you are writing a complicated syntax for something that can be solved with two lines of code, the power of destructuring can only be understood by someone who uses it for all possible applications. According to MDN:
“The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.”
This brings me to my next point, most people think that destructuring is only for spreading arrays but that's, not the case. In JavaScript Object is king, the array you create is also an object for JS, how that works is out of scope for this article. But destructuring is something that can be applied for both js arrays and objects. In this article, we will go through some of the most common applications and techniques for destructuring. We will take a look at examples for each - With/Without destructuring to understand better.
1. Basic Array destructuring
Nothing fancy here, basic destructuring is something that would be required regularly and the most overlooked for writing code that goes against the DRY principle of clean code. Nothing fancy here, just an array with three strings and extracting them one by one to three separate variables based on their position.
Without destructuring
With Destructuring
As you can see above by using array destructuring we can write the same piece of code in one line. We used the same line of code to extract the three array values and assign them to their respective variables. This is the most common use case for destructuring arrays.
2. Destructuring to split arrays
We just learned basic destructuring, now let’s apply that to a more general task. If we have an array with say 6 elements, we wish to extract the first element from the array and also create a new array with the last five elements. Normally we can create a new variable, assign the element at position zero to it and then create another variable where we will store the second part of the array after slicing it using the operator.
Without Destructuring
With Destructuring
As you can see above we used destructuring to extract the first element and also create a new array with the rest of the items. We can use the same technique if we need to extract more individual variables as well, as long as we are using the spread operator only on the last item in the destructured array on the left side.
3. Destructuring with default values
We just learned basic destructuring, but there can be scenarios where the assigned variable becomes undefined due to some error like length mismatch. In such cases, we can provide a default value while destructuring. In the below example we are trying to assign variables ‘a’ & ‘b’ from an array of length 1. As you can see we have defined default values for both variables in the same line which is why ‘b’ is not undefined but rather prints 7 which is the default value.
Default Value with Destructuring.
4. Swapping Values
This is a very interesting use case for destructuring. Swapping values of two variables using normal methods will require using a temporary variable or some mathematical operations to be performed on both variables. If the scenario is swapping values at different positions within an array, it required even more steps. This is where one of the most simple but efficient uses of destructuring can be applied.
Swapping with destructuring
In the above code, we swap the value of two variables ‘a’ & ‘b’ without using any temp or math operations by destructuring. We just need to wrap the variables on the left side array, and they will automatically take the value of the variable at the corresponding position on the left side. This can be observed in the second example where swap values between ‘a’, ‘b’ & ‘c’ as well in just one line. And the last example shows how to swap values at two positions within an array, where we are swapping values at position 1 and position 2 of the array.
5. Function parameters
Another place where we can use destructuring in function parameters. Let’s consider the following example. We have a function that takes firstName & lastName of a user as parameters and returns a complete string with the full name. As you can see normally we may pass the parameters for the function is by calling the function and passing the two arguments separately as per the function definition. But the problem with this approach is that every time we call the function we have to pass the variable names separately, and if the number of variables is more than one or two the code can look messy.
Without Destructuring
With Destructuring
In the above code, if you check the function definition you can see that we have added array destructuring to the parameters in the function definition itself. This way we can call the function by directly using the array and not having to pass separate elements or repeat the same code again and again.
6. Function return value
Just like function parameters, we can also use destructuring efficiently on functions that return an array as well. Consider the following example, where we have a function that returns an array of two elements. To get the values we may first store them in an array variable and extract them separately.
Without Destructuring
With Destructuring
Here we directly declare and assign the array elements to ‘a’ & ‘b’ using array destructuring in one line.
7. Basic Object destructuring
We learned about common array destructuring techniques, but what if we have an object with few properties and we need to extract some properties to a variable so that we don’t have to call the object. property name every time we need to use it. The same technique we used for arrays can be applied for objects as well. Consider the following piece of code, where we have an object with 4 properties and we need to extract three of them to individual variables. This is how we will write it conventionally.
Without destructuring
With destructuring
But as you can see above, using object destructuring we can reduce the same into a single line of code to extract and assign values to new variables at the same time.
8. Object with a new name or default value
Basis destructuring may not be used all the time with objects as it looks a little redundant to declare object properties and destructure them to variables with the same names. But the object destructuring can be applied to more use cases that you can see in the below example.
- Destructuring and renaming the new variable.
- Destructuring and providing default values for undefined properties.
- Destructuring with new variable names and default values.
9 . Combined Array and Object Destructuring
Let’s see how we can combine array and object destructuring for a common use case. For example, if you want the third element in an array of objects, and then you want to access a property in the particular object. We can combine array and object destructuring to access the property quickly and efficiently.
As you can see we are accessing usernames from different user objects in the users array by destructuring and also renaming the properties like our last example. If you observe the name:FirstUserName
you can see that we have wrapped it in an object which is wrapped in an array and two trailing commas (,,). The commas are a key part here, as it defines the position of the object from the array that we are trying to access.
To clarify further, for firstUsername, we had two trailing commas after the object, for secondUserName we had one comma before and after the secondUserName object and two preceding commas for the third user name ( see code snippet). You could improvise more and even assign default values for the properties while destructuring.
That’s it about destructuring techniques in JavaScript for now. I believe most of the everyday use cases have been covered. For the sake of article length, we have omitted a few very similar ones. If you have more destructuring techniques that you believe will add value, please add them in responses.
More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord.