Modern JavaScript has many new features that make it easy to write code in a simple and structured manner. One of the handy modern features available in ES6+ is array and object destructuring.
JavaScript frameworks like React.js and Angular encourage the use of this technique. So it’s essential to understand what destructuring is all about and how to use it while writing code.
What Is Object and Array Destructuring in JavaScript?
Destructuring in JavaScript refers to the process of unpacking values from an array or object. It provides a more concise way of getting values from arrays or objects without heavy lifting when you're interested in individual array items or values in an object.
It's also helpful when processing returning values from a complex function or expression. This concept is one of the best practices you should follow while writing React code.
How to Destructure Arrays
Here's a sample code to get a sense of array destructuring:
const arr = [1, 2];
const [a, b] = arr;
console.log(a) // prints 1 on the console
console.log(b) // prints 2 on the console
This code uses destructuring to assign the values from arr—1 and 2—to the variables a and b, respectively. This is the fundamental concept behind destructuring. You have an array or object on the right-hand side, and you unpack items and assign them to individual variables on the left-hand side.
Under the hood, JavaScript copies values from arr and assigns them to the variables on the left-hand side like so:
const arr = [1,2];
const a = arr[0];
const b = arr[1];
As you can see, destructuring is a more concise way of doing this, unlike using the object or bracket notation. However, this syntax will likely be useful when working with complex arrays or functions that return arrays or strings.
Check the sample code below:
const [day, month, date, year, time, timezone] = Date().split(' ')
// Calling Date() returns the current date in the format:
// Mon Feb 20 2023 13:07:29 GMT+0000
console.log(day) // prints Mon
console.log(month) // prints Feb
console.log(date) // prints 20
In this code sample, we're creating a new string with the current date by calling Date(). Next, we use split(), a JavaScript string method, to separate items in the string using space as the separator. split(' ') returns an array, and we use destructuring to assign the values to individual variables.
Remember that if your array contains more items than you're unpacking, JavaScript will ignore the extra items.
const arr = [1, 2, 3, 4];
const [a, b] = arr;
console.log(a) // prints 1
console.log(b) // prints 2
// values 3 and 4 are not assigned to any variable; they are ignored
In this case, if you want to store the remaining items in a variable, use a rest parameter like so:
const arr = [1, 2, 3, 4];
const [a, b, ...rest] = arr;
console.log(rest) // prints [3,4]
Sometimes, you may not care about a specific item. JavaScript's destructuring pattern also allows you to skip certain elements by using an empty comma.
const arr = [1, 2, 3, 4];
const [a, , c] = arr;
console.log(c) // prints 3
The code above uses the empty space to ignore value 2 in the array arr. Instead of assigning value 2 to variable c, it skips to the next item in the array. It also ignores the fourth value because it doesn't specify a variable to store it in.
In contrast, if you need fewer items than you're unpacking, the process will assign the undefined value to those extra variables.
const arr = [1];
const [a, b] = arr;
console.log(a) // prints 1
console.log(b) // prints undefined
To prevent having variables undefined, you can set default values if you're not sure about the array length as follows (assigning default values is not a requirement):
const arr = [1];
const [a = '10', b = 'not provided'] = arr;
console.log(a) // prints 1
console.log(b) // prints "not provided"
This destructuring assigns the value 1 to variable a, overwriting its default value. Variable b keeps its default because a value is not provided.
How to Destructure Objects
Destructuring objects is not so different from arrays. The only difference is that arrays are iterable and objects are not, resulting in a slightly different way of doing things.
When working with objects, the variables on the left-hand side of the assignment operator are also initialized like objects:
const person = {name: 'Alvin', age: 10, height: 1};
const {name, age, height} = person;
console.log(name) // prints 'Alvin'
console.log(height) // prints 1
From the code, we're using property names from the person object. However, you don't have to use the exact property names in the object. You can destructure and store the values in different variable names as follows:
const person = {name: 'Alvin', age: 10, height: 1};
const {name: firstName, age: years, height: currentHeight} = person;
console.log(firstName) // prints 'Alvin'
console.log(currentHeight) // prints 1
You start by specifying the property value you want to destructure, then specify the variable name you will use to store the value after a colon. And like arrays, destructuring a property name that doesn't exist will be undefined.
To handle this, you can similarly specify default values in case the property name you want to assign to a variable is not available:
const person = {name: 'Alvin', age: 10, height: 1};
const {name, age, height, location='Worldwide'} = person;
console.log(name) // prints 'Alvin'
console.log(location) // prints 'Worldwide'
The order of variables on the left-hand side doesn't matter with an object since the objects store values in key-value pairs. As such, the following code will yield the same results:
const person = {name: 'Alvin', age: 10, height: 1};
const {age, height, name} = person;
console.log(name) // prints 'Alvin'
console.log(height) // prints 1
Lastly, similar to arrays, you can also use the rest parameter to destructure several values in one variable like so:
const person = {name: 'Alvin', age: 10, height: 1};
const {name, ...rest} = person;
console.log(name) // prints 'Alvin'
console.log(rest) // prints { age: 10, height: 1 }
Just note that the rest parameter must always come last. Otherwise, JavaScript will throw an exception.
Improve Your Code Quality With JavaScript’s Destructuring
Javascript's modern features, like destructuring, enable you to write highly readable code. Using destructuring, you can quickly unpack values from arrays and objects. Destructuring can also prove handy in other situations, like swapping values of two variables. Hopefully, you now understand what destructuring means in JavaScript, and you can be able to use it while writing code.