In javascript, objects are commonly used to store multiple data in a single variable. This provides a very compact and convenient way to operate on the data, especially, when passing the data to other parts of the application code. Javascript provides a very convenient means to extract the value of each data when needed.
In Javascript, we can use the object destructuring method to extract the values of multiple properties from an object in just a single statement. It eliminates the need to for multiple statements when accessing the values of multiple object properties. The object destructuring approach has less typing and saves time.
Javascript object destructuring can also be used to perform other object operations such as cloning, extending, updating, and merging other objects.
This post takes an in-depth look at ES6 Javascript object destructuring technique, with emphasis on clarity and working examples for better understanding.
Table of Contents
- Object Destructuring Assignment
- Object Destructuring Assignment Syntax
- Understanding Object Destructuring
- Mismatch Variable Name in Property Keys is undefined
- Setting Default Values
- Destructuring into Declared Variables
- Aliasing Declaration Variables
- Extracting Rest of Properties Into a Variable
- Using Spread Syntax in Object Destructuring
- Destructuring Function Parameters
- Destructuring Nested Objects
- Summary
Object Destructuring Assignment
In Javascript, object destructuring assignment is an expression that makes it possible to extract some or all properties of an object into specific variables. It was introduced in ES6 (ECMAScript 2015) as a means to simplify the extraction of properties from objects and arrays. It can also be used to destructure strings.
Before its introduction, we would extract the values of object properties by typing the name of the object variable followed by the dot (.
) operator, and then the property we want to access.
For example, let’s suppose we have an object data that contains information about a user:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
We can access the values of the object properties using the dot (.
) notation:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
// extract values
const name = User.name;
const email = User.email;
const role = User.role;
Another approach involves specifying the property names as a string enclosed in square brackets, []
, following the property name:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
// extract values
const name = User['name'];
const email = User['name'];
const role = User['name'];
Both approaches, however, involve more typing to access property values. For example, each access to a property value requires its own statement. Additionally, we always need to type the object variable name, square brackets, and property name in each statement to access a property value. All these lead to more typing, especially when we have to access multiple object property values.
But ES6 Javascript has a better and compact approach to do this, called object destructuring. With ES6 Javascript object destructuring, we can extract all or some of the property values of the User
object in just a single statement:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
// extract values
const { name, email, role } = User;
Line 9 in listing 4 does the trick. It is called object destructuring assignment. In just a single statement, we have been able to extract all the property values that we need. We did not have to type multiple object variable name, square brackets, and property keys. This approach is much of less typing and saves time.
In the discussions that follow, we will delve deeper into Javascript object destructuing. Before that, we should look at the very basic syntax of Javascript object destructuring assignment.
Object Destructuring Assignment Syntax
In Javascript object destructuring assignment, an object from which we want to extract property values is assigned to declared variables. The declaration variables into which the values of the object properties are stored are enclosed in braces, {}
, on the left-hand side of the assignment operator.
For example, in listing 4, the statement on line 9 is object destructuring assignment. In this assignment, the User
object is destructured into individual properties, and the values of these properties are assigned to the declaration variables enclosed in curly braces.
Unlike in Javascript array destructuring, the order of the declaration variables is not important in object destructuring. Shortly, we will know how Javascript is able to tell which property values to store in each of the declaration variables.
Looking again at line 9 in listing 4, we can tell that an object destructuring assignment has the following basic syntax:
// destructure object into variables
let { var1, var2, var3 } = ObjectData
In this assignment syntax, var1
, var2
, and var3
are declaration variables into which the values of properties in ObjectData
will be stored. As seen, the declaration variables are enclosed in braces, {}
. This is in contrast to array destructuring assignment syntax, which uses square brackets, []
, to enclose declaration variables.
We can even use the const
declaration keyword for the declaration variables:
// destructure object into variables
const { var1, var2, var3 } = ObjectData
Understanding Object Destructuring
Javascript object destructuring is a programming technique that makes it possible to extract multiple object property values into variables a single statement. It eliminates the need for dedicated statements for each property value access, and has less typing than property access with the dot notation.
What makes this approach so handy is that we can declare multiple variables and use the object variable name only once in an assignment. Javascript does the job of extracting the property values into these declared variables.
Consider the code listing below:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
With Javascript ES6 / ECMAScript 2015, we can extract muiltiple properties into variables in just a single statement whiles using the User
object name only once in an assignment:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
// extract property values into variables
const { name, email, role } = User;
console.log(name); // output: Daniel
console.log(email); // output: dan@mail.com
console.log(role); // output: Developer
The order of the variables in the declaration does not matter. We can declare the target variables in any order:
// extract property values into variables
const { role, name, email } = User;
console.log(name); // output: Daniel
console.log(email); // output: dan@mail.com
console.log(role); // output: Developer
If the order of the declaration variables does not matter, then how is Javascript able to map the declaration variables to the object properties and extract their values? The answer is simple. By default, Javascript expects the declaration variable names to match property keys in the object being destructured.
For example, in the object destructuring statement,
const { name, email, role ] = User;
the declared variable name
, email
, and role
match property key names in the User
object.
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
By this, Javascript is able to map the variable names to the object property keys and extract their values. Later, we will see how we can specify variable names that are not property keys in the object being destructured.
Remember from our discussion on destructuring assignmnent syntax that we use braces, {}
, to declare target variables when destructuring an object. By default, the variable names enclosed in the braces are the names of the properties that we want extract.
If a variable name exists in the destructuring declaration but is not found as a property or key in the object being destructured, then the value for that variable will be undefined
. We delve more into this next.
Mismatch Variable Name in Property Keys is undefined
We have indicated that, in object destructuring, the variable names in the destructuring declaration should match property keys in the the object that is being destructured. We have already seen this in listing 8.
But what if we type a declaration variable name which does not exist as a key in the properties of the object being destructured? Well, let’s see what happens.
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
const { username, email, role } = User;
// log values
console.log(username); // output: undefined
console.log(email); // output: dan@mail.com
console.log(role); // output: Developer
On line 8, the username
variable in the declaration variables does not match any name in the User
object property keys. The remaining declaration variable names, email
and role
, however have matching names in the User
object property keys.
Since username
does not match any property key in the User
object, there will be no value to extract into the username
variable. Therefore its value will be undefined
, as seen in its output on line 11.
Thus, if variable name in the destructuring declaration is not found as a property key in the object being destructured, then the value of that variable will be undefined
.
Setting Default Values
If there is a possibility for the value of a property to be undefined
, then we can set a default value that should be used. We do this by assigning the default value to the target variable in the destructuring statement. The following listing is an example:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: undefined
};
const { name, email = 'user@mail.com', role = 'Data Analyst' } = User;
// log values
console.log(name); // output: Daniel
console.log(email); // output: dan@mail.com
console.log(role); // output: Data Analyst
On line 6, we have deliberately set the value of the role
property to undefined
. In the variables declaration on line 8
, we have set default values for email
and role
. After object destructuring, we can see from the log values that the default value for role
has been used since the extracted value from the role
property in the User
object is undefined
.
The default value for the variable email
, which is user@mail.com
, was not used since the email
property of the User
object is not undefined
. Thus, the default value is used when the value extracted from an object property is undefined
.
Destructuring Into Existing Variables
In the examples that we have covered so far, we have extracted the property values into newly declared variables:
// delcare variables
const { name, email, role } = User;
The const
keyword preceding the declaration variables is an indication that we are declaring new variables.
If we have existing variables whose names match property key names in the object, then we can specify the existing variables in the destructuring statement. In this case, there will be no need to precede the destructuring statement with const
or let
. However, there is one more thing to take into account. We will need to enclose the whole statement in parenthesis before that will work:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
// variables declration
let name, email, role;
// destructure object into the existing variables
({ name, email, role } = User);
The variables name
, email
, and role
are declared on line 9. Then on line 12, we specify these existing variables in the destructuring statement. You should observe that we have enclosed the destructuring assignment in parenthesis, ()
. Without the parenthesis, an error will be generated.
For example, the following statement destructures the User object into existing variables without the statement being enclosed in parenthesis:
// destructure object into the existing variables
{ name, email, role } = User;
Destructuring an object into existing variables without the statement being enclosed in parenthesis, like on line 2, will generate the following error:
If we intend to destructure an object into already declared variables, we will need to enclose the destructuring assignment expression in parenthesis, ()
.
Aliasing Declaration Variable Names
In listing 8, we understood that, by default, we are compelled to declare variables with names that match object property key names when destructuring an object. If a variable name in the declaration does not match a property key in the object being destructured, its value will be undefined
.
But what if the object property keys are not descriptive enough to be used as variables in the current scope? Or what if we prefer a different name for the variable?
Consider the following object data:
// object declaration
const User = {
n: 'Daniel',
e: 'dan@mail.com',
r: 'Developer'
}
Some applications that transmit data through networks use shortened names rather than descriptive and long property key names. The aim may be to reduce the size of data transmitted over the network.
If we are to destructure an object with non-destructive property keys, such as in listing 16, by default, we will be compelled to use these non-descriptive property keys as variables in the application.
// initialize object data
const User = {
n: 'Daniel',
e: 'dan@mail.com',
r: 'Developer'
};
const { n, e, r } = User;
// log values
console.log(n); // output: Daniel
console.log(e); // output: dan@mail.com
console.log(r); // output: Developer
Luckily, ES6 Javascript allows us to specify alias names for object property keys. We can use these alias names to refer to the properties in the object being destructured.
To specify an alias name when destructuring an object, we separate the declaration variable name and the alias name with a colon, (:
) . For example:
// initialize object data
const User = {
n: 'Daniel',
e: 'dan@mail.com',
r: 'Developer'
};
const { n: name, e: email, r: role } = User;
// log values
console.log(name); // output: Daniel
console.log(email); // output: dan@mail.com
console.log(role); // output: Developer
Once an alias name is specified, we cannot use the actual variable name in the application logic. For example, the following will generate an error:
console.log(n);
This produces a ReferenceError
. Since we have specified an alias name for the variable n
, we can no longer use it in the application scope where it is declared. To Javascript, such variable does not exist:
A problem arises if a property that needs to be extracted has the same name as a variable already declared in the current scope. Consider the following code listing:
// email variable declration
let email = 'default@mail.com';
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
// extract values from the User object
const { name, email, role } = User;
This code listing will generate a syntax error when run. A sample error can be seen below:
The User
object contains a property with the key email
. Meanwhile, in the destructuring assignment on line 12, the declaration attempts to create variables, including email
, But email
is an existing variable declared on line 2. This generates the syntax error since a variable with name email
already exists.
The solution to such problem depends on whether we can overwrite the value in the existing variable, email
, or not.
If we do not want to overwrite the value in the existing variable, then we will need to provide an alias name for the email
property:
// extract values from the User object
const { name, email: userEmail, role } = User;
// log values
console.log(email); // output: default@mail.com
console.log(userEmail); // output: dan@mail.com
However, if we wish to overwrite the value in the existing variable, email
, then we will need two statements to extract the values: one to declare the new variables for assignment, and the other to assign to the existing variable:
// extract into existing variable
({ email } = User);
// extract into new variables
const { name, role } = User;
Since email
is already declared, we only perform the assignment by enclosing the statement in parentheses. However, name
and role
are new variables and therefore we declare them with the const
keyword. We could also have used let
or var
to accomplish same.
Extracting Rest of Properties into a Variable
Sometimes, we may wish to extract the values of some properties into specific variables and then pack the rest, or remaining properties into another variable. ES6 Javascript provides the rest operator to do this.
The rest operator is a three consecutive dot (...
) operator that is used to precede a declaration variable name to signify that the remaining properties that have not been extracted yet, should all be extracted and packed into the variable preceded by the rest operator.
For example, if we want to extract the name
property into a variable and extract the remaining properties into another variable, we will have to use the following destructuring statement:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
const { name, ...theRest} = User;
console.log(name); // output: Daniel
console.log(theRest); // output: { email: 'dan@mail.com', role: 'Developer' }
On line 8, the value of the name
property of the User
object is extracted into the name
declaration variable. The rest operator, (...
), preceding theRest
variable implies that, the remaining properties which have not been extracted yet should all be extracted and packed into theRest
variable.
With the rest operator preceding theRest
variable, Javascript packs the remaining properties into the variable for us. One important thing to note is that the variable preceded with the rest operator must be the last element in the declaration variables. The following statement is wrong and will generate a syntax error:
const { ...theRest, name } = User;
The following syntax error will be generated since the rest operator is applied to a variable element which is not the last:
Another important thing to note is that, the variable into which the properties are packed is always an object. This is so even if there is only one property packed into it. Let’s see an example below:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
const { name, email, ...theRest} = User;
// log value of theRest
console.log(theRest); // output: { role: 'Developer' }
On line 8, we apply the rest operator to theRest
variable. At this point, the name
and email
have already been extracted, with only role
remaining and packed into theRest
. The log on line 11 reveals that theRest
is actually an object
, although only one property was extracted into it. Thus, if we precede a declaration variable with the rest operator, then the type
of the variable is always an object
.
Using Spread Syntax in Object Destructuring
The spread syntax is ES6 Javascript expression that expands the properties of an object into individual parts. Like the rest syntax, the spread syntax is a three consecutive dot (...
) operator preceding an object variable that expands the properties of the object.
The spread syntax can be used to perform operations such as merging multiple objects, cloning, updating, and extending an object.
Cloning Objects
The ES6 Javascript spread syntax can be used to make a shallow clone of an object so that an update to one object reference does not affect the other object.
Suppose we have the following object data:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
If we assign the User
to another variable, both variables will have the same reference to the object data.
// assign the User object to another variable
const anotherUser = User;
console.log(anotherUser === User); // output: true
In this case, an update to the data using one variable will affect the other variable. To make a shallow clone of the User
object so that they will have the same data but different references, we will need to clone the User
object.
With ES6 Javascript, we can use the spread syntax to clone the User
object.
// make a copy of the User object
const anotherUser = {...User};
The spread operator expands the properties of the User
object and places them between the braces, {}
. This creates a new object with a different reference, and the newly created object is assigned to anotherUser
.
Although User
and anotherUser
have the same data values, they have different references, and an update to one does not affect the other. Thus, we can use the ES6 Javascript spread syntax to clone an object.
Extending Objects
We can use the ES6 Javascript spread syntax to extend an object. This is particularly helpful if there are multiple properties to be added to an existing object data.
In the pre-ES6 era, we could do this by using the dot (.
) notation to extend an object with new properties, or use Object.assign()
to add new properties:
// initialize an object
let data = {
name: 'Daniel'
};
// add new properties
data.email = 'dan@mail.com';
data.role = 'Developer';
The following code listing uses the spread syntax to extend an existing object:
// initialize an object
let data = {};
// add new properties
data = { ...data, email: 'dan@mail.com', role: 'Developer' };
Line 5 initializes a new object by spreading or expanding the current properties of data
, and then includes email
and role
properties in the new object. In this example, we assign the newly initialized object to data
. Sometimes, we may need to assign the newly initialized object to a different variable.
Updating Objects
Although we can use the dot (.
) notation to update object property values, if we need to update multiple values, we will need multiple statements to do this:
// initialize object data
let User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
// update property values with dot notation
User.name = 'Emmanuel';
User.email = 'emma@mail.com';
Before ES6 Javascript, we could also achieve this in a single statement using Object.assign()
method. However, we can use the spread syntax to achieve the same in just a single statement:
// initialize object data
let User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
// update property values with dot notation
User = { ...User, name: 'Emmanuel', email: 'emma@mail.com' };
console.log(User); // output: { name: 'Emmanuel', email: 'emma@mail.com', role: 'Developer' }
Merging Objects
If we have multiple objects that we need to merge into one object, we can easily do so using the Javascript spread syntax. To do this, we will need to initialize a new object and spread the properties of the objects that we need to merge in the initializer object.
For example, suppose we have the following objects, A
and B
:
// Object A
const A = {
name: 'Daniel',
email: 'dan@mail.com'
};
// object B
const B = {
role: 'Developer',
address: {
city: 'Kumasi',
region: 'Ashanti'
}
}
We can merge objects A
and B
into another object using the spread syntax. To do this, we spread the properties of objects A
and B
in a new object that we initialize:
// merge A and B into a new object
const User = { ...A, ...B };
// log User object
console.log(User);
From the log output below, we can see that the User
object contains all the properties of objects A
and B
:
The properties of objects A
an B
were merged into the User
object.
Destructuring Function Parameters
ES6 Javascript provides a very convenient way to destructure object parameters in a function. That is, we can destructure function parameters that are objects.
Before ES6 Javascript, we would access object properties from function parameters such as in the following code listing:
function showUser(userParam) {
let name = userParam.name;
let email = userParam.email;
let role = userParam.role;
// log values
console.log(name); // output: Daniel
console.log(email); // output: dan@mai.com
console.log(role); // output: Developer
}
Rather than access the property values into new variables, we can destructure and bind the parameter object properties into new variables directly in the function header: To understand this better, we should understand that when we pass a value to a function, the argument value is assigned to the function parameter.
Given the User
object used in earlier examples, we can pass it to the showUserInfo()
function as follows:
showUserInfo(User);
As indicated earlier, passing a value to a called function assigns the function argument to the function parameter, as if we have done the following:
userParam = User;
userParam
is the parameter variable in the function header, and User
is the object passed as argument. But since User
is an object, we can destructure it into defined variables, as we have already been doing, as follows:
{ name, email, role } = User;
With ES6 Javascript, we can replace userParam
in the function header with the declaration variables { name, email, role }
. Thus, we can rewrite the showUserInfo()
function as follows:
function showUserInfo({ name, email, user }) {
// log values
console.log(name); // output: Daniel
console.log(email); // output: dan@mai.com
console.log(role); // output: Developer
}
As can be seen, destructuring object parameters in function headers has less typing and saves time.
Destructuring Nested Objects
We can extend the understanding gained so far in Javascript object destructuring to destructure objects nested within an object. Destructuring nested objects is simple, although it may seem challenging at first.
Let’s revisit our User
object data which we have used for the examples in previous discussions:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer'
};
We will extend this User
object by adding an address
property:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer',
address: {
city: 'Kumasi',
region: 'Ashanti'
}
};
We can identify that the value of the address
property is an object. Thus, we have an object within an object. Let’s suppose that we want to extract city
, and region
into variables.
In the pre-ES6 Javascript era, we could extract the city
and region
from the address
property using the dot notation, such as in the following code listing:
// extract city and region
let city = User.address.city;
let region = User.address.state;
With ES6 Javascript object destructuring, we can extract these values into variables in just a single statement. We will take step by step approach to better understand nested object destructuring.
When destructuring a nested object, we need to specify the property key name followed by colon, :
, then the declaration variables enclosed in braces:
const { nestedObjectProperty: { DECLARATION_VARIABLES }};
Think of the specification of the property key name as directing Javascript to the nested object which we want to destructure.
For example, in our User
object in listing 41, the nested object has the property key name address
, hence we will specify this property key name, followed by colon, ( :
), then the declaration variables:
const { address: { DECLARATION_VARIABLES }} = User;
One key trick in destructuring nested objects is to isolate the nested object to be destructured, whiles taking note of its property key name. In our example, the value of the address
property is an object, and we can isolate the address
object as follows:
address = {
city: 'Kumasi',
state: 'Ashanti'
}
Given this address
object, we can use our normal destructuring technique to extract the values of city
and region
into variables as follows:
const { city, region } = address;
As can be seen, destructuring the address
property in isolation gives us { city, region }
, which we can use to replace { DECLARATION_VARIABLES }
in listing 41.
const { address: { city, region }} = User;
That is really simple, isn’t it?. The only extra typing here is the specification of the address
property key name. It is however important since this is a clue to Javascript to know which specific nested object to look and extract property values.
The following code listing is a working example of what we just covered:
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer',
address: {
city: 'Kumasi',
region: 'Ashanti'
}
};
// extract city and region from User object
const { address: { city, region }} = User;
console.log(city); // output: Kumasi
console.log(state); // output: Ashanti
In another example, we will attempt to extract name
, email
, and city
from the User
object. We should remember that city
is found in a nested object with property name address
, which is found in User
object.
The following statement extracts name
, email
, and city
from the User
object.
// extract name, email, and city
const { name, email, address: { city }} = User;
Since name
and email
are not properties in nested object, we do not precede their declaration variables with property key names. However, city
is a property found in a nested object, hence we precede the declaration variable with address:
. As indicated earlier, this a hint to Javascript to know where to perform the nested object destructuring.
Let us consider another example that is also simple to do, but maybe a bit challenging. We will introduce a location
object, nested in the address
object, which is also nested in the User
object.
// initialize object data
const User = {
name: 'Daniel',
email: 'dan@mail.com',
role: 'Developer',
address: {
city: 'Kumasi',
region: 'Ashanti',
location: {
street: 'XYZ Avenue',
house: 'P8 BLK5'
}
}
};
We have added a location
object, spanning from line 9 to line 12, to the address
object which is also nested in the User
object. If we need to extract the values of name
, city
, and street
properties, the following statement will do:
// extract name, city, and street
const { name, address: { city, location: { street }}} = User;
// log values
console.log(name); // output: Daniel
console.log(city); // output: Kumasi
console.log(street); // output: XYZ Avenue
Let’s break down the object destructuring statement on line 2 to have a better understanding.
We can identify from the User
object in listing 50 that, the value of name
property is basic type, string in this case. Since this is not a nested object, we can extract its value directly without preceding it with a property name:
// extract name, city, and street
const { name, ... } = User;
city
is a property found in a nested object with property name address
. To extract its value, we need to specify the property key name address
, and separating the declaration variable with a colon ( :
):
// extract name, city, and street
const { name, address: { city } } = User;
Lastly, we can identify that the street
property is found in the location
object. Since location
is a nested object, we will specify its name and the declaration variable as: location: { street }
.
But location
is nested in address
object. We will therefore need to include it in the declaration for the address
property. Thus, we will have the following destructuring statement:
// extract name, city, and street from User
const { name, address: { city, location: { street }}} = User;
// log values
console.log(name); // output: Daniel
console.log(city); // output: Kumasi
console.log(street); // output: XYZ Avenue
The destructuring statement on line 2 extracts name
, city
, and street
from User
.
Summary
Javascript object destructuring is a programming expression that extracts the values of object properties into declared variables. It can be used to extract the values of multiple object properties into variables in a single statement.
const Student = {
id: 1,
name: 'Emmanuel',
email: 'emma@mail.com'
}
// extract property values in a single statement
const { id, name, email } = Student;
By default, Javascript expects the declaration variable names to exist as property keys in the object being destructured. If a declaration variable name does not exist as a property key in the object being destructured, then the value of the variable will be undefined:
const Student = {
id: 1,
name: 'Emmanuel',
email: 'emma@mail.com'
}
// extract property values in a single statement
const { stdId, name, email } = Student;
// log stdId
console.log(stdId); // outut: undefined
As can be seen, the first declaration variable has the name stdId
. However, the Student
object does not contain a property key with this name. Therefore, the value of stdId
will be undefined
since it does not have a matching property key name in the Student
object.
If we wish to use a different name as variable than the property key name in the object, then we can provide an alias name to be used:
const Student = {
id: 1,
name: 'Emmanuel',
email: 'emma@mail.com'
}
// extract property values in a single statement
const { id: stdId, name, email } = Student;
// log stdId
console.log(stdId); // output: 1
On line 8, we specify an alias name, stdId
, for the id
property in Student
object. The value of the id
property is extracted into stdId
. When we set an alias name, we cannot use the property key as a variable for the same value: An attempt to do this leads to a ReferenceError
:
// log id
console.log(id); // ReferenceError: id is not defined
When destructuring an object, we can set default values for variables into which extracted values are saved. The default values are used if the value of the variables are undefined
after destructuring.
Consider the following code listing:
const Student = {
id: 1,
name: 'Emmanuel',
email: 'emma@mail.com'
}
// extract property values in a single statement
const { id, name, email, programme } = Student;
console.log(programme); // output: undefined
Observe that the fourth declaration variable, programme
, does not exist as a property key in the Student
object. As we have already indicated, the value of programme
will be undefined
. We can specify a default value that should be used rather than undefined
by assigning the default value to the variable in the destructuring statement:
const Student = {
id: 1,
name: 'Emmanuel',
email: 'emma@mail.com'
}
// extract property values in a single statement
const { id, name, email, programme = 'Pharmacy' } = Student;
console.log(programme); // output: Pharmacy
We can also apply object destructuring to destructure object parameters in function headers:
function show({ id, name, email }) {
console.log(name);
console.log(email);
}
show({ id: 1, name: 'Emmanuel', email: 'emma@mail.com' });
Other operations that can be performed with Javascript object destructuring include the use of spread syntax to extend, merge, clone, and update objects, as well as pack multiple properties into a single variable with the rest operator.
We can also apply object destructuring technique to destructure nested objects.