Object Literals and Spread Operator

Image for post
Image for post

In this tutorial we will learn how to take advantage of spread operator in order to initialise a new object with optional properties.

Let’s start from a very basic example. We can create a new object with following key-value notation:

However, we can convert values into variables:

Overall, the result is the same.

If we take advantage of ECMAScript2015 notation we can simplify it even further:

Now, let’s create a scenario when one of the properties is optional. We want to return the same object if all values are set or remove optional property:

This will however, yield:

While what we expect to get is:

There are a few techniques available that will give the correct and expected result. However, one of the coolest is to use spread operator:

Which returns:

With spread operator we achieved exactly what we wanted! However, how did that work?

Basically, logical AND operator && returns object {b} to spread operator if condition b is true and this will be true for all objects b that havetruthy value. If the value is falsy then no object will be returned to spread operator.

If you like this tutorial then please like, share and follow me. If you have questions or maybe you have a different technique please don’t be afraid to comment below.

Written by

Programming, project management and politics

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store