Subscribe to my email list now at http://jauyeung.net/subscribe/
Follow me on Twitter at https://twitter.com/AuMayeung
Many more articles at https://medium.com/@hohanga
Even more articles at http://thewebdev.info/
JavaScript, like any other programming language, has many handy tricks that let us write our programs more easily. In this article, we will look at how to decomposing object properties and array elements into individual variables, merging multiple objects into one, and manipulate URLs with the URL
object.
Decompose Object Properties and Array Elements
With ES6, we can use shortcuts to assign values of an object into its own variable and also assign individual array entries into their own variables. Thanks to the destructuring assignment syntax, we can do this without retrieving the object key-value pair explicitly or array entry explicitly by its index.
The simplest way to use it on objects is to write something like:
const {
a,
b
} = {
a: 1,
b: 2
};
With the code above, the JavaScript interpreter will match the key name on the right to the variable name on the right. This way, it can assign 1 to a
and 2 to b
. We can also assign the value on the right to a variable with a different name on the left. To do this, we can write the following code:
const {
a: foo,
b: bar
} = {
a: 1,
b: 2
};
The code above will first match the key name on the right to the key name on the left, then it will funnel the value that matches those keys to the variable on the right of the colon on the left side.
This means that the a
key on the right will be matched with the a
key on the left. This means that the value for a
on the right which is 1, will be assigned to the variable name that’s the value of the a
key, which is foo
.
Likewise, the b
key on the right will be matched with the b
key on the left and the value of the b
key on the right will be assigned to the variable name that corresponds to the b
key on the left. So in the end, what we get is that the variable foo
is 1 and the variable bar
is 2.
We can assign default values to the variables on the left side so that we don’t have to worry about them being undefined
after the destructuring assignment operation.
To do this, we write the following to set the default value on the variables on the left side with the =
operator like typical assignment operations. For example, we can set default values to the variables on the left like in the following code:
const {
a = 0,
b = 0
} = {
a: 1
};
console.log(a, b);
If we log the values of a
and b
like we did above, we should get 1 for a
and 0 for b
since we didn’t assign any value for b
on the left side, so the default value of 0 which we specified is automatically assigned to the value of b
like we specified it.
Likewise, we can use the destructuring assignment syntax with arrays. We can use it as in the following code:
const [a, b] = [1, 2];
With arrays, the JavaScript interpreter will match the position of the variable to the array entry in the position that the variable names are in. So the first array entry on the right will be assigned the first variable name on the left, and the second array entry on the right will be assigned to the second variable name on the left and so on. We can also use it to swap variable values like in the following code:
let a = 1,
b = 2;
[a, b] = [b, a];
If we run console.log
on a
and b
after the destructuring assignment, we get that a
is 2 and b
is 1. This is very handy since we don’t have to assign our variables to a temporary variable to swap the value of variables.
We can also assign default values to variables that are in the arrays when we use them in the destructuring syntax so that we can don’t have to worried about variables being undefined
after assigning them values with the destructuring syntax. For example, we can write:
let a,b;
([a=1,b=2] = [0])
This is a valid syntax. In the code above, we get that a
is 0 because we assigned 0 to it. b
is 2 because we didn’t assign anything to it.
Merging Multiple Objects into One
With the spread operator, we can use it to merge multiple objects into one. Before we had the spread operator, we have to loop through the keys of each object and then put the key-value pairs of each object manually with our own code into a new object, and we have to do that for all the objects that we want to merge together.
This was a real pain. But now, with the spread operator syntax, we can just apply the spread operator in each object in a new object, then we get a new object with all the keys of the new object. For example, if we have these objects:
const obj1 = {
a: 1,
b: 2
};
const obj2 = {
c: 3,
d: 4
};
const obj3 = {
e: 5,
f: 6
};
const obj4 = {
g: 7,
h: 8
};
const obj5 = {
i: 9,
j: 10
};
Then we can use the spread operator to merge them together like in the following code:
const obj1 = {
a: 1,
b: 2
};
const obj2 = {
c: 3,
d: 4
};
const obj3 = {
e: 5,
f: 6
};
const obj4 = {
g: 7,
h: 8
};
const obj5 = {
i: 9,
j: 10
};
const mergedObj = {
...obj1,
...obj2,
...obj3,
...obj4,
...obj5
};
Then when we log the value of mergedObj
, we get:
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
"g": 7,
"h": 8,
"i": 9,
"j": 10
}
If we have objects with some or all keys that are the same as each other, then the value of the overlapping key that’s merged in later will overwrite the one that was merged in earlier. For example, if we have:
const obj1 = {
a: 1,
b: 2
};
const obj2 = {
a: 3,
d: 4
};
const obj3 = {
a: 5,
f: 6
};
const obj4 = {
g: 7,
h: 8
};
const obj5 = {
i: 9,
j: 10
};
const mergedObj = {
...obj1,
...obj2,
...obj3,
...obj4,
...obj5
};
Then when we log the value of mergedObj
, we get:
{
"a": 5,
"b": 2,
"d": 4,
"f": 6,
"g": 7,
"h": 8,
"i": 9,
"j": 10
}
As we can see, the value of property a
is 5. This is because we first merged in obj1
with the value of a
being 1, then we merged in obj2
, which has the value of a
being 3, which overwrote the original value of 1, then after we merged in obj3
, which has the value of a
being 5, this overwrote the value of 3 that was merged in before. Therefore, we get the final value of 5 for a
.
Manipulate URLs
With the URL object, we can pass in a URL string and extract and set various parts of a URL and get a new URL. We can create a URL object by using the constructor.
The constructor takes up to 2 arguments. Either we have one argument being the complete URL string, or we can pass in a relative URL string which is part of the complete URL as the first argument and the first part of the complete URL string, or the hostname, as the second argument. For example, we can either write:
new URL('http://medium.com');
or
new URL('/@hohanga', 'http://medium.com');
With the URL object, we can get and set various properties to get a part of the URL and also set parts of the URL to create a new URL. With the hash
property, we can set the hash part of the URL, that is, the part of the URL after the pound sign (#
). For example, we can write something like the following code:
const url = new URL('http://example.com/#hash');
console.log(url.hash);
url.hash = 'newHash';
console.log(url.toString());
If we run the code, we can see that the first console.log
statement logs '#hash'
. Then we assigned the value 'newHash'
to the url
‘s hash
property. Then when we run the toString()
method on the url
object and the run the console.log
method on the value returned by toString()
, we get 'http://example.com/#newHash'
which is the new value of the URL with the new hash.
Likewise, we can change the hostname, which is the first part of the URL, by setting the host
property. Like the hash
property, the host
property also has a getter function to get the URL’s hostname. For example, we can write something like the following code:
const url = new URL('http://example.com/#hash');
console.log(url.host);
url.host = 'newExample.com';
console.log(url.toString());
If we run the code, we can see that the first console.log
statement logs 'example.com'
. Then we assigned the value 'newExample.com'
to the url
‘s host
property. Then when we run the toString()
method on the url
object and the run the console.log
method on the value returned by toString()
, we get http://newexample.com/#hash’
which is the new value of the URL with the new hostname.
There are more properties in the URL object. Stay tuned for the next part where we explore more parts of the URL object.
JavaScript, like any other programming languages, have many handy tricks that let us write our programs more easily. In this article, we looked at how to decomposing object properties and array elements into individual variables, merging multiple objects into one, and manipulate URLs with the URL
object. With these tricks, we reduce the effort we put into writing our code making our lives easier.