Javascript Object literal conditional properties
Toncho Dev
Posted on July 8, 2019
Original post at toncho.dev
We constantly coming up against adding conditional properties to an Object
, but always end doing:
const a = {};
if (someCondition) {
a.b = 5;
}
To deal with this in an elegant way we are going to use the spread operator
and short-circuit evaluation
, with the enhancements ES6 has brought to the Object
.
const a = {
...someCondition && { b: 1 },
}
In JavaScript, expressions using the &&
and ||
operators get checked for possible short-circuit evaluation
, &&
operator will only evaluate to true if both conditions are truthy. If the first one if falsey, then the second condition won’t even get evaluated. the ||
operator will only evaluate to false if both condition are falsey. If the first condition is truthy, the second won’t get evaluated. Additionally, the &&
and ||
operators actually return the value of the last expression that gets evaluated in the statement.
Now if someCondition
is truthy will return { b: 1 }
and false if someCondition
is falsey, the returned value then gets spread into the object, so if the expression returns falsey will not be spread at all, and no new keys are added to the object.
Posted on July 8, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024