Introduction
As a Javascript developer, you will work with different data types on a daily basis including objects.
Objects help in storing data in a structured manner. Objects can also represent real-world objects like dogs.
When it comes to objects, data is stored in properties, each property having a value.
Therefore, when working with objects in Javascript, you will often need to extract specific properties from an object.
Object destructuring is a syntax introduced in ES6 that provides a net way of assigning values taken directly from an object.
Object destructuring is useful for writing clean and readable code.
In this guide, you will explore object destructuring step by step.'
When you are done reading, you will be able to streamline your Javascript code using object destructuring.
Pre-requisites
Before we continue with this guide, you should have the following requirements:
- Basic understanding of HTML AND CSS. Get Started with HTML and CSS
- Knowledge of basic Javascript. You can get started with Javascript basics here
- Knowledge of how to use the console to write your javascript code learn how to use Google console to run Javascript
- Understand basic ES6 syntax including arrow functions
Basic destructuring using assignment operator
Destructuring assignment is a special syntax in ES6 that enables us to extract properties from an object and assign them to variables in one line.
For example, consider the object below:
const user ={
firstName: "John",
lastName: "Doe",
age:25,
}
In ES5, you could extract properties like this;
const firstName = user.firstName;
const lastName = user.lastName;
const age = user.age;
In this example,
firstname
would have the value of the string John,lastName
would be Doe, andage
would have the value of the number 25.
Using ES6 object destructuring syntax, the following is the equivalent code:
const {firstName,lastName,age } = user;
Again, here,
firstname
would have the value of the string John,lastName
would be Doe, and age would have the value of the number 25.Note: You can extract as many or as few values from an object as you want
Assign variables to properties while destructuring
Object destructuring allows you to assign variables to properties when extracting values.
To do this, put a new name after a colon when assigning the value.
<!-- Javascript code -->
const user ={
firstName: "John",
lastName: "Doe",
age:25,
}
Here is how you can give a new variable to a property:
const {firstName: userFirstName, lastName:userLastName, age : userAge} =user;
You may read this code as:
- Get the value of
user.firstName
and assign it to a variable nameduserFirstName
. - Get the value of
user.lastName
and assign it to a variable nameduserLastName
. - Get the value of
user.age
and assign it to a variable nameduserAge
.
Again the variable userFirstName would have the value of the string
John
,userLastName
would have Doe, anduserAge
would have the value of the number 25.
Assign variables to nested objects
Sometimes you will work with an object that contains other objects inside it which we refer to as object nesting.
We can use ES6 syntax to destructure values from a nested object.
To achieve this, we will nest johnDoe
as an object inside a user
object.
const user = {
johnDoe :{
age:25,
email:"johndoe@gmail.com"
}
};
In the above code, we have a user object that has johnDoe object nested within it.
- Firstly, here is how you can extract the values of the object's properties and assign them to variables with the same name:
<!-- Javascript code -->
const { johnDoe: {age, email}} = user;
- Secondly, here is how you can assign an object's properties values to variables with different names:
<!-- javascript code -->
const {johnDoe:{age:userAge, email:userEmail}} = user;
Use Destructuring assignment to assign variables from Arrays
Destructuring assignment is not limited to objects. We can also destructure values from arrays just as we have done with objects.
The following example shows how you can use destructuring assignment to assign variables from arrays.
<!-- JavaScript code -->
const myName= ["Dennis", "John", "Doe"]; // an array of names
Here is how to use destructuring assignment and assign variables from the arrays:
<!-- JavaScript Code -->
const[firstName, secondName,lastName] = MyName;
- The variable
firstName
would have the value of the stringDennis
.- The variable
secondName
would have the value of the stringJohn
.- The variable
lastName
would have the value of the stringDoe
.
Destructuring via rest elements
Sometimes in array destructuring, you may want to collect the rest of the elements in a separate sub-array.
The rest parameter allows functions to accept an indefinite number of arguments as an array.
read more on rest paremeter in JavasScript.
In the following example, we have an array that contains 3 colors.
const [firstColor,secondColor, ...remainingColors] = ["red", "green", "blue", "yellow", "black"];
when you console.log the variables, the following values are displayed:
console.log(firstColor); // red
console.log(secondColor); // green
console.log(remainingColors); // ["blue", "yellow", "black"]
Variables firstColor and secondColor takes the first and second values from the array. After that, because of the presence of the rest syntax, remainingColors gets the remaining colors in the form of an array.
Use destructuring assignment to pass an object's properties as function parameters
With object destructuring, you can pass object's properties as function's parameters. Doing this ensures your code is readable.
Let me explain how to do this :
Firstly, we have an object personDetails
with properties and values.
const personDetails = {
name:"John Doe",
age: 25,
email:"johndoe@gmail.com"
}
Secondly, we define an arrow function showPersonInfo
that takes an object with properties name
, age
, and email
as its parameter.
when the function is called, it logs a string that contains the person's name, age, and email.
const showPersonInfo= ({name, age, email})=>{
console.log(` My name is ${name}.I am ${age} years old. contact met via ${email}`);
}
Thirdly, we invoke showPersonInfo
function and pass the personDetails
object as an argument.
By doing this, you have extracted the name
, age
, and email
properties from personDetails
. You now can access and use the properties inside the function's body.
<!-- javascript code -->
console.log(showPersonInfo(personDetails)); // My name is John Doe.I am 25 years old. contact me via johndoe@gmail.com
Conclusion
I hope you enjoyed this article. You have learned object destructuring which is an important javascript technique. We have learned how to extract specific values from an object's properties.
Along the way, we have understood how object destructuring enhances code clarity by reducing redundancy hence boosting developer efficiency.
I hope you will use this newly gained knowledge as you continue your Javascript journey.
Written by: Dennis Mbugua
Follow me on Twitter
Top comments (0)