Explore the destructuring assignment syntax
In this article, I am going to explain what the destructuring assignment is in JavaScript. But first, let’s see what an object property value shorthand is.
Object Property Value Shorthand
In ES6, if you have an object whose keys have the same name as the variables that are passed in as properties, you can use the object property value shorthand to simplify your code.
const data = { test: '123' };
const test = { data: data };
We can simplify the code above like this:
const data = { test: '123' };
const test = { data };
It’s a small feature that makes our code cleaner!
Destructuring Assignment Syntax
Destructuring assignment syntax is an expression that unpacks values from arrays and object properties into variables. It sounds strange, but it’s not! In essence, we break a structure (destructure) into individual elements, e.g., an array to array items.
Get data from an array
Let’s assume that we have an array with two elements:
const array = [1, 2];
And we want the value of the first element to be stored in a variable named “a” and the value of the second element to a variable named “b.”
const a = array[0];
const b = array[1];
With destructuring, we can do it like this:
const [a, b] = array;
In destructuring, the left part of the expression is called the target, and the right is called the source.
Keep in mind that for the destructuring to work the target and the source must have the same data structure.
With destructuring, we can easily skip items from arrays. Here’s the code:
const array = [1, 2, 3];
const [a, , b] = array;
Now the a has the value 1, and the b has the value 3. We can add as many commas as we want, but after the two commas in a row, it’s not readable.
Let’s assume that we have an array with nine items:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
And we want the value of the first element to be stored to a variable named “a”, the value of the second element to a variable named “b”, and the rest of the array to a variable named “c”.
We can easily do this with the help of the reset parameter. If you don’t know what a reset parameter is, don’t worry, read this.
const [a, b, ...c] = array;
console.log(a); // 1
console.log(b); // 2
console.log(c); // [3, 4, 5, 6, 7, 8, 9]
Swap variable values
Let’s assume that we have two variables and we want to swap their values. Here’s the code:
let a = 1;
let b = 2;
const temp = a;
let a = b;
let b = temp;
With destructuring, we can easily do it without the temp variable:
let a = 1;
let b = 2;
let [b, a] = [a, b];
We created the same data structure (array) in the source and the target. It’s a simple trick for swapping.
Destruct function return value (array)
Let’s assume that we have a function that returns an array of two items:
const data = () => [1, 2];
And we want the value of the first element to be stored to a variable named “a” and the value of the second element to a variable named “b”.
const value = data();
const a = value[0];
const b = value[1];
With destructuring, we can simplify the above and remove the value variable:
const [a, b] = data();
Add default values
Let’s assume that we have an array that sometimes has two values and sometimes has one value.
const array = [1];
We want the value of the first element to be stored to a variable named “a” and the value of the second element to a variable named “b”. Also when the array has only one value, the variable “b” will have the value “1”.
const a = array[0];
const b = array[1] || 2;
The old way to do this is with the logical operator. If you don’t know what a logical operator is, don’t worry read this.
With destructuring, we can do it like this:
const [a, b=2] = array;
Keep in mind that this works only in the case that the unpacked value is undefined
or it’s not there at all. So if the value is something falsy, e.g. null, false e.t.c, it will not use the default value.
Get data from an object
Let’s assume that we have the object:
const user = { name: 'George', email: '[email protected]' };
And we need two variables “name” and “email” with the values of the user object.
const name = user.name;
const email = user.email;
With destructuring, we can do it like this:
const { name: name, email: email } = user;
The above works perfectly because the source and the target have the same data structure. But we can use the object property value shorthand to write this in a more simplified way.
const { name, email } = user;
The extended way is helpful when we want the variables to have a different name than the properties, e.g., “userName”, “userEmail”:
const { name: userName, email: userEmail } = user;
Get data from an object with the rest parameter
Let’s assume that you have the object:
const user = {
name: 'George',
role: 'SA',
killingZombies: true,
dancing: true
};
And we need a variable “name” with the user name, a variable “role” with the user role, and a variable “hobbies” with an object that contains all the user hobbies.
With destructuring, and the rest parameter we can do it like this:
const { name, role, ...hobbies } = user;
Destruct function return value (object)
Let’s assume that we have a function that returns an object:
const data = () => ({ name: 'George', role: 'SA' });
And we need a variable “name” with the user name and a variable “role” with the user role.
const value = data();
const name = value.name;
const role = value.role;
With destructuring, we can simplify the above and remove the value variable:
const { name, role } = data();
Destruct a function parameter
Let’s assume that we have this function:
function (currentUser) {
const name = currentUser.name;
const email = currentUser.email;
const roles = currentUser.roles;
console.log('Name', name);
console.log('Email', email);
console.log('Roles', roles);
}
We can optimize the above by destructuring the function parameter:
function ({ name, email, roles }) {
console.log('Name', name);
console.log('Email', email);
console.log('Roles', roles);
}
We created all the variables in the parameter section and now the code is more readable.
As you can see the destructuring assignment syntax in JavaScript is very powerful and can optimize/simplify our code.