Object Destructuring in JavaScript
Introduction
Conventionally before ES6, the common way to create a variable from something that is inside of an object was by assigning each variable individually or Iterating through them. This method is pretty much repetitive and limits our ability to manipulate our data object more effectively. Let me show you what I mean with an example.
The example below shows a person
object with three properties: name
, occupation
, and town
.
const person = {
name: 'Ada',
occupation: 'Banker',
town: 'Lagos',
}
As we mentioned earlier, to either get access to each property (name
, occupation
, and town
) or create a new variable for each property, we would have to assign each variable individually, with a lot of repetition as seen below:
const name = person.name;
const occupation = person.occupation;
const town = person.town;
In order to avoid repetition of this sort , we would need to destructure the object. This brings us to our topic of discourse- Object Destructuring. The primary aim of this article is to teach us the different ways to destructure objects in JavaScript with concrete examples and use cases.
Object Destructuring - A Primer
In JavaScript, Destructuring is one of the many key features introduced since the 2015 Edition of the ECMAScript specification. There are basically two types - Array and Object Destructuring.
In this article, however, we will be focusing only on Object Destructuring. Object Destructuring is the process of creating new variables from an object where the name of the variable is something we define and the value is the corresponding value on that object.
Destructuring is a great feature that allows us to extract properties from an object at a time.
To Destructure the object from our example above, we would simply surround each variable with curly braces {}
and create new variables from each property with the same name. Let's see how to do so below:
// Create a person object
const person = {
name: 'Ada',
occupation: 'Banker'
town: "Lagos"
}
// Destructure properties into values
const {name, occupation, town} = person
From the above example, we can see how we've extracted the properties in our object using object destructuring with just a single line of code as opposed to performing actions on them individually. Therefore with destructuring assignment, the equivalent code becomes more concise and readable.
Note: Object Destructuring not only allows us to write cleaner code and avoid repetition but also avails us a quicker way to sort out object properties into variables.
Now let's log out the new variables below:
console.log(name)
console.log(occupation)
console.log(town)
See output below:
//Output
Ada
Banker
Lagos
Use Cases of Object Destructing
The main purpose of Object Destructuring is to improve our code and simplify it at the same time. Now, let us look at some of the use cases of performing object destructuring in JavaScript.
Assigning values to variables (Independent from their declaration)`
One of the key usefulness of Object Destructuring is that it allows us to assign default values to variables with the undefined property.
Let us see what we mean with an example below:
let person= {
firstName: "Samson",
lastName: "Fredrick",
occupation: "lecturer"
}
let {
firstName,
lastName,
age = 30,
occupation
} = person;
We have assigned our user object person
three properties, firstName
, lastName
, and occupation
. Note that the age
property is not part of the user object, thus it is not defined. This, however, doesn't stop us from creating a new variable off the object person
and assigning a value to it. This is well explained in the above lines of code as we added a new variable age
to our person
object and assigned it a value 30
.
When we console.log() the age
property we would see that we've successfully assigned a new value to it.
Let's have a look below:
// Output
Samson
Fredrick
30
lecturer
Computing Object Property Names
Another interesting feature about Object Destructuring is that it allows us to compute a property name while changing its name like on Object Literals. This means that we can put an expression in []
that will be computed and used as the property name.
Let's see how to do so below:
let key = 'm';
let {[key]: zap} = {m: 'bud'};
This is what we will get when we log zap
on the console
console.log(zap)
bud
In the above example, we computed the key
variable and changed its name to zap.
Destructuring Function Return Statements
JavaScript object destructuring can be used to destructure values that a function is returning. What do we mean here? Let's take a look at the example below.
function getUserInformation() {
return{name: 'Whitey', race: 'Caucasian", profession: "spy"}
}
const {name} = getUserInformation();
In the above example, we have successfully destructured the return value of our getUserInformation
function by specifying the value we want to be returned, which in this case is name
. When we console.log(name), we will get the below output.
// Output
Whitey
Swapping Variables
With Object Destructuring, it is possible to swap the values of variables. Amazing right? Let's take a look at the example below.
let firstName = "Samson";
let lastName = "Fredrick";
[firstName, lastName] = [lastName, firstName];
console.log(firstName); //Fredrick
console.log(lastName); //Samson
Ignoring Returned Values/ or Skipping Items
We can use Object Destructuring to skip some values in our variables that are not useful to you. As usual, let's explore how to do so below:
function j() {
return [10, 20, 30];
}
let [k, , m] = j();
console.log(k); // 10
console.log(m); // 30
Destructuring Nested Object
In JavaScript, when we have an object that is inside another object, we call that Nested Object. For example, assuming that we have an employee
object which has a name
object as property:
let employee = {
id: 1631,
name: {
firstName: 'Samson',
lastName: 'Fredrick'
}
};
The code underneath destructures the properties of the nested name
object into individual variables:
let {
name: {
firstName,
lastName
}
} = employee;
console.log(firstName); // Samson
console.log(lastName); // Fredrick
It will also interest you to know that you can equally do multiple assignment of a property to multiple variable. Let me show you how:
let employee = {
id: 1631,
name: {
firstName: 'Samson',
lastName: 'Fredrick'
}
};
let {
name: {
firstName,
lastName
},
name
} = employee;
//Output
console.log(firstName); // Samson
console.log(lastName); // Fredrick
console.log(name); // { firstName: 'Samson', lastName: 'Fredrick' }
Notice how you can easily manipulate your Object data using Destructuring? I'll leave you here to try the various use cases on whichever application you're working on now, let the examples be your guide and make sure you have fun as you do.
Conclusion
JavaScript as we already know, have an object-based paradigm which have properties associated with it. These properties defines the features of the object and can be accessed using Object Destructuring which we have already covered above.
From the beginning, we got to understand how repetitive and unreadable our code will be if we stuck with the old way of extracting or creating new variables from an object. Following that, we got to see how easy it is to create variables from an object using destructuring and how easily flexible we can manipulate our data objects using different use cases such as assigning values to variables, swapping variables, destructuring function return statement, computing object property names and a host of others.
On a final note, as developers, effort should be geared towards writing clean and easy-to-read code. Making your code more readable and easier to understand is the beauty of destructuring and by extension, Object Destructuring.
I want to reiterate that although Destructuring allows us to pull one or many properties from an object into a separate variable, it covers a broader spectrum. Do not forget that it can be used with Arrays as well(which I will cover in-depth in my next article). It can also be used within loops, inside functions and much more as we have seen in the examples above.
References
JavasScript Object Destructuring
I hope this was explanatory enough. Any question or addition? Please leave a comment.
Thank you for reading :)