Destructuring assignment and Spread operator are my favorite ES6 features. Today I want to show you two pro tips that you can use to write clean code.
Remove unwanted properties
Sometimes you might need to write a function to convert an object to a different structure, and you might want to remove some properties from the object as you don't need them. Instead of directly deleting the properties from the object, you can use object destructuring to remove unwanted properties. See the code below.
function makeVeggieBurger(hamburger) {
// 😞
delete hamburger.meat
return hamburger
// 😃
const { meat, ...veggieBurger } = hamburger
return veggieBurger
}
Here it uses object destructuring on hamburger
, and gets meat
property and puts all the other properties in veggieBurger
. When it returns veggieBurger
, it returns a shallow copy of hamburger
without meat
. This approach avoids mutating the original object, but achieves the same result with only a line of code.
Conditionally add properties to an object
Continue with the example above, but this time we add a new parameter isSpicy
to indicate if we want to add chili to the burger. If isSpicy
is true, we want to add chili
property to veggieBurger
, but if isSpicy
is false, we don't want to have chili
property at all. See the code below.
function makeVeggieBurger(hamburger, isSpicy) {
const { meat, ...veggieBurger } = hamburger
// 😞
if (isSpicy) {
veggieBurger.chili = 'hot'
}
return veggieBurger
// 😃
return {
...veggieBurger,
...(isSpicy && { chili: 'hot' }),
}
}
Let's take a close look at this
return {
...veggieBurger,
...(isSpicy && { chili: 'hot' }),
}
If isSpicy
is true, it will be like
return {
...veggieBurger,
...(true && { chili: 'hot' }),
}
which is
return {
...veggieBurger,
...{ chili: 'hot' },
}
And as we spread it, it becomes
return {
...veggieBurger,
chili: 'hot'
}
This is how you add chili
to the returning object.
If isSpicy
is false, it will become
return {
...veggieBurger,
...(false && { chili: 'hot' }),
}
which is
return {
...veggieBurger,
...false
}
and when you spread false
, it returns nothing, so this expression becomes
return {
...veggieBurger,
}
which essentially is
return veggieBurger
So we won't have chili
at all. This approach will make you code much cleaner especially when you add multiple properties conditionally.
That's it. I hope you find it helpful. Feel free to let me know if you have any questions. You can also find me on twitter.
Top comments (0)