Since 2015, JavaScript has improved immensely.
It’s much more pleasant to use it now than ever.
In this article, we’ll look at the best features of ES2018.
Rest Operator on Objects
We can use destructuring with the rest operator in objects.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
};
const {
a,
...rest
} = obj;
Then a
is 1 and rest
is:
{
"b": 2,
"c": 3
}
If we’re using object destructuring to handle named parameters, the rest operator lets us collect all the remaining parameters.
So if we write:
function foo({
a,
b,
...rest
}) {
console.log(
a,
b,
rest
);
return a + b;
}
foo({
a: 1,
b: 2,
c: 3
})
Then a
is 1, b
is 2, and rest
is {c: 3}
.
We can use the rest operator for destructuring at most once and only at the end.
This makes sense since it’s the only way JavaScript engines know what hasn’t been assigned to a variable yet with destructuring.
So we can’t write:
const {...rest, a} = obj;
or:
const {foo, ...a, ...b} = obj;
They both will give us syntax errors.
We can nest the rest operator.
For instance, we can write:
const obj = {
qux: {
a: 1,
b: 2,
c: 3,
},
foo: 4,
baz: 5,
bar: 6,
};
const {
qux: {
a,
...rest1
},
...rest2
} = obj;
Then a
is 1, rest1
is {b: 2, c: 3}
.
And rest2
is {foo: 4, baz: 5, bar: 6}
.
Spread Operator in Object Literals
The spread operator in object literals is new to ES2018.
For instance, we can use it by writing:
const obj = {
a: 1,
b: 2
};
const obj2 = {
...obj,
baz: 3
}
We used the spread operator to copy the properties of obj
into a new object and assigned it to obj2
.
So obj2
is {a: 1, b: 2, baz: 3}
.
The order matters since they’ll be populated in the order they’re spread.
So if we have:
const obj = {
a: 1,
b: 2
};
const obj2 = {
baz: 3,
...obj
}
Then obj2
is {baz: 3, a: 1, b: 2}
.
The 2 keys clash, then the later one overwrites the earlier ones.
So if we have:
const obj = {
a: 1,
baz: 2
};
const obj2 = {
baz: 3,
...obj
}
Then we get:
{baz: 2, a: 1}
as the value of obj2
.
Uses of the Object Spread Operator
The object spread operator has a few use cases.
One of them is to clone an object.
For instance, we can write:
const obj = {
a: 1,
b: 2
};
const clone = {
...obj
};
Then a shallow copy of obj
is made with the spread operator and so clone
is:
{
a: 1,
b: 2
}
This is the same as using Object.assign
to do the cloning;
const obj = {
a: 1,
b: 2
};
const clone = Object.assign({}, obj);
Spread is shorter and cleaner.
Conclusion
The object rest and spread operator are great new operators that are released with ES2018.
It’s clean and convenient.