Sitemap

Member-only story

Object Literals and Spread Operator

2 min readAug 14, 2018

--

Press enter or click to view image in full size

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:

const object = {
a: 'foo',
b: 123,
c: { obj: 'bar' }
};

However, we can convert values into variables:

const value1 = 'foo';
const value2 = 123;
const value3 = { obj: 'bar' };
const object = {
a: value1,
b: value2,
c: value3
}

Overall, the result is the same.

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

const a = 'foo';
const b = 123;
const c = { obj: 'bar' };
const object = {
a,
b,
c
}

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:

const a = 'foo';
const b = undefined; // Optional
const c = { obj: 'bar' };
const object = {
a,
b,
c
}

This will however, yield:

Object {a: "foo", b: undefined, c: {obj: "bar"}}

--

--

Arek Jaworski
Arek Jaworski

Written by Arek Jaworski

Software Architect — AWS/Node.JS/JavaScript Contractor and Tutor. Combing industry experience with research!