Web Dev Stories
AboutArticlesProjectsBookmarksContact

written on 07/16/2019

Adding object properties conditionally with EcmaScript 6 (ES6)

This was a tweet recently by an engineer from Google who is working on the V8 engine powering the Google Chrome web browser and Node.js. It got me to think what use-cases are extremely helpful for me and that I should share them with the world here.

Adding a property to an object

Adding a property to an object is quite easy in JavaScript. You can basically do it like in the following code.

1
const person = {
2
firstName: "Max",
3
};
4
person.lastName = "";

But imagine the lastName should just be added if there is a specific conditional.

1
const person = {
2
firstName: "Max",
3
};
4
5
const condition = getCondition();
6
7
if (condition) {
8
person.lastName = "";
9
}

This still looks fine but what if we combine conditions and add them into multiple if blocks?

1
const person = {
2
firstName: "Max",
3
};
4
5
const condition = getCondition();
6
const additionalCondition = getAdditionalCondition();
7
8
if (condition) {
9
person.lastName = "";
10
}
11
12
if (additionalCondition) {
13
person.addition = "";
14
}

It looks a lot harder to read overall and a function with this code would grow a lot even though it is just doing simple things.

EcmaScript 6 (ES6) is a new standard which enables a lot of new features in the language JavaScript. With those features, we could write the following code.

1
const condition = getCondition();
2
const additionalCondition = getAdditionalCondition();
3
4
const person = {
5
firstName: "Max",
6
...(condition && { lastName: "" }),
7
...(additionalCondition && { addition: "" }),
8
};

The result of the value of person would be the same as in the script mentioned above. But how does this work?

The && operator

&& is a logical operator in JavaScript and is combining boolean values by using AND . It can be used with two parameters. Let us assume those parameters are a and b . When we apply the && parameter it would look like a && b . This will result in a boolean as a result which can be either true or false. It will be true if both of the parameters are also true . If one, or both, are false the result will be false too.

1
const a = true;
2
const b = true;
3
const result = a && b;
4
console.log(result);
5
// Will log true
1
const a = false;
2
const b = true;
3
const result = a && b;
4
console.log(result);
5
// Will log false
6
7
const c = false;
8
const d = false;
9
const result = c && d;
10
console.log(result);
11
// Will log false

A specialty is also that when not using booleans for a or b it can happen that no boolean is getting returned. We can simply check this by using the browser console.

1
const a = true;
2
const b = "Magic String";
3
const result = a && b;
4
console.log(result);
5
// Will log "Magic String"

We can extend this feature and also return an object which is super nice.

1
const condition = true;
2
const result = condition && { lastName: "" };
3
console.log(result);
4
// Will log { lastName: "" }

But somehow we need to merge this object into the person object above 🤯

Merging Objects

Merging objects is possible for a long time already in JavaScript with the Object.assign functionality.

1
const basePerson = {
2
firstName: "Max",
3
};
4
const person = Object.assign({}, basePerson, { lastName: "" });

What happens here is that the last parameter { lastName: ""} gets merged into the object basePerson. If properties would be the same the last object would win and overwrite the property of the preceding object. Also Object.assign is mutable function. This means it will apply all changes to the first parameter in all parameters of the function. To avoid changes to the basePerson object we pass an empty object as the first parameter, so a new object is being created rather than an old one which is reused.

EcmaScript 6 (ES6) offers a nicer way to do these merges.

1
const basePerson = {
2
firstName: "Max",
3
};
4
5
const person = {
6
...basePerson,
7
lastName: "",
8
};

This would result in the same person object as before with the properties firstName and lastName. Also, here the last properties are overwriting the first properties, but we still have a problem of applying the object returned in the && expression into the object because the current version assumes that lastName is just a key and has a static value.

We can pass an object to be destructured though into the person object to actually pass an object rather than key and a value.

1
const basePerson = {
2
firstName: "Max",
3
};
4
5
const person = {
6
...basePerson,
7
...{ lastName: "" },
8
};

This might be enough now to refactor and put in a variable but we have one problem as const result = condition && { lastName: "" }; could result in either false or { lastName: "" }. If we pass the object ...{ lastName: "" } to the destructuring function everything is fine but what is happening if we pass something like ...false in?

JavaScript being clever
JavaScript being clever

Actually, this would result in nothing when being used in an object. This also means we can use it in the big destructuring functionality.

1
const basePerson = {
2
firstName: "Max",
3
};
4
5
const condition = getCondition();
6
const result = condition && { lastName: "" };
7
// Can be either false or { lastName: "" }
8
9
const person = {
10
...basePerson,
11
...result,
12
};
13
// Can be { firstName: "Max" } or { firstName: "Max", lastName: "" }

This is super nice but can be still improved by inlining the result somehow.

1
const basePerson = {
2
firstName: "Max",
3
};
4
5
const condition = getCondition();
6
7
const person = {
8
...basePerson,
9
...(condition && { lastName: "" }),
10
};

This is a super slick example on how to extend objects conditionally in JavaScript and really shows that when using modern language we can use a more crisp syntax to express ourself.

These functions become especially important when you create the same type of object, sometimes with some properties and sometimes not. Think of factory functions for unit or integration tests.

If you are interested in more JavaScript content, check out my blog articles Add or delete a property of an object in JavaScript, How to debug JavaScript applications and tests or Function parameters in JavaScript.

You might also like

© Kevin Peters 2021

Imprint