Destructuring in Javascript

Darshana Sandaruwan
5 min readNov 14, 2020
Figure 1

In the life of day to day programming with javascript, most of the developers need to access items/elements inside objects/arrays. Destructuring comes here to give an easy way to access keys/elements of objects/arrays in javascript. How does the mechanism of destructuring works with arrays & objects?

  1. Object Destructuring

Destructuring an object is assigning values of object keys to a particular declaring variable. Please consider the below object,

const user = {
name: 'Darshana',
country: 'Sri Lanka',
};
In normal way we can access name and the country of the user by accessing object by it's keys (objectName.key).// to get the name the user => user.name;
// to get the country of the user => user.country;
When destructuring comes to objects,it assigns the values of the keys of the right hand side object to the relevant variable name of the left hand side object key. It's as below,const { name, country } = user;// to get the name the user => name;
// to get the country of the user => country;

2. Object Destructuring with Renaming Variables

Renaming variables while destructuring would be something interested as there can be multiple variables that need to make the same name. On this point, renaming is perfect while destructuring.

const student = {
name: 'Darshana',
location: 'Sri Lanka',
};
In your current context, you would have declared name or location variable. In that case, destructuring student object would occur conflicts on name, location variables. As a solution for this, renaming with object destructuring is handy. Below is the example for renaming keys of the object.const { name: fullName, location: country } = student;In the above destructuring method with renaming, name & location are undefined. Here we can access name via fullName & location via country. Below would be the outputs of the consoles,console.log(name); //output Uncaught ReferenceError: name is not defined
console.log(location); //output Uncaught ReferenceError: location is not defined
console.log(fullName); //output Darshana
console.log(country); //output Sri Lanka
Here name has been renamed to fullName and location has been renmaed to country. So we must access fullName & country instead of name, location.

3. Object Destructuring with Default Values

When destructuring objects sometimes you don’t know whether the object has specific keys or not. It’ll generate an issue if we try to destructure an undefined key in the object. If we try so, it’ll break up the program. As an answer for this, default values are assigned while destructuring.

const vehicle = {
brand: 'BMW',
model: 'i8',
year: '2019',
};
If we try to destructure vehicle and get brand, model & year, sure we'll do it and get the values of each variables.
But what will happen if we try to destructure company object inside vehicle object.
const { company } = vehicle;
console.log(company); //output undefined
Sometimes we would be accepting a 'company' object with multiple keys inside vehicle object. In this case, we definitly try to destructuring 'company' object also.const { company: { name, owner } } = vehicle;console.log(name); //output Uncaught TypeError: Cannot read property 'name' of undefined
console.log(owner); //output Uncaught TypeError: Cannot read property 'owner' of undefined
As company is not declared within vehicle object we cannot destructure company object. Therefore it's better to assign a default value to that doubtfull property.const { company: { name, owner } = { name: 'Bayerische Motoren Werke AG', owner: 'Stefan Quandt' } } = vehicle;If name or owner properties aren't defined in the company object, it'll assign name and the owner values of the other object which is assigned as the default values. It'll avoid generating Cannot read property 'name' of undefined.

4. Array Destructuring

We access array indexes using the array[index]. In array destructuring, we can do the same thing by assigning specific index values to variables.

const users = ['John', 'James', 'Andrew', 'Mark'];We can access oth index of users array by users[0].console.log(users[0]); // outputs John
console.log(users[1]); // outputs James
console.log(users[2]); // outputs Andrew
console.log(users[3]); // outputs Mark
When destructuring users array,
const [ first, second, third, fourth ] = users;
console.log(first); // outputs John
console.log(second); // outputs James
console.log(third); // outputs Andrew
console.log(fourth); // outputs Mark

There are different ways of implementing array destructuring.

const users = ['Alex', 'Andy', 'Rocky', 'Rolex'];
let [first,,,last] = users;
console.log(first); // outputs Ales
console.log(last); // outputs Rolex
let [first, ...rest] = users;console.log(first); // outputs Alex
console.log(rest); // outputs ['Andy', 'Rocky', 'Rolex']

5. Array Destructuring with Default Values

When destructuring arrays it’s a good way to input default values to array destructuring to avoid code break up when destructuring undefined indexes.

const users = ['Darshana'];const [first, second = 'Sandaruwan'] = users;console.log(second); //outputs Sandaruwanusers array only have 0thindex. In desctruturing we're gonna access oth & 1st indexes. Initially it doesn't have 1st index. Therefore we added default value to 1st index of the array while destructuring the array.

Example

const person = {
age: 27,
name: 'Darshana',
country: 'Sri Lanka',
bio: {
height: 5.5,
weight: 60,
color: 'brown',
},
schools: [
{
name: 'Sunanda Primary College',
address: 'Kalutara',
},
{
name: 'Pothupitiya Maha Vidyalaya',
address: 'Wadduwa',
},
{
name: 'Sumangala Boys College',
address: 'Panadura',
},
],
}

when we access some of the values of the person object there are multiple levels of data for the person. How we access each property of the person in a normal way is like below.

Normal Access of a property

// access first levels of the objectconst name = person.name; // object name (person) . key (name)
const age = person.age; // object name (person) . key (age)
console.log(`name => ${name}, age => ${age}`);
//output name => Darshana, age => 27

// access second levels (object) of the object
const height = person.bio.height; // object name (person) . object name (bio) . key (height)
const weight = person.bio.weight; // object name (person) . object name (bio) . key (weight)
console.log(`height => ${height}, weight => ${weight}`);
//output height => 5.5, weight => 60

Way of Object destructuring

// access first levels of the object
let { name, age } = person;
console.log(`name => ${name}, age => ${age}`);
//output name => Darshana, age => 27
// access second levels (object) of the object
let { name, age, bio: { height, weight }} = person;
console.log(`height => ${height}, weight => ${weight}`);
//output height => 5.5, weight => 60

Way of Array destructuring

const { schools: [first, second, third] } = person;console.log(first); // outputs {
name: 'Sunanda Primary College',
address: 'Kalutara',
}
console.log(second); // outputs {
name: 'Pothupitiya Maha Vidyalaya',
address: 'Wadduwa',
}
console.log(third); // outputs
{
name: 'Sumangala Boys College',
address: 'Panadura',
}

This is the basics of javascript destructuring which is better to access properties of objects & arrays. Destructuring is much more efficient and improved readability rather than accessing objects & arrays via keys & indexes.

--

--

Darshana Sandaruwan
0 Followers

I am an ambitious and positive person who enjoys taking up challenges in the field of Software Engineering