Ever had a situation where you wanted to conditionally add an attribute to a javascript object and you had to use let
instead of const
and add an if condition just because of that? I am talking about this:
let userProps = {
username: "rad-coder"
}
if (userIsBanned) {
userProps.banned = true
}
return userProps
In the above code, if there was no conditional attribute, userProps
wouldn't have been needed. If there are multiple attributes like that, that means more if conditions and code.
Simpler Alternative
Instead of using the if statement, you can use the spread operator. The idea is simple: the spread operator merges the properties of the target object with the object it's being applied on and if the source object is null, it adds no properties.
const x = { ...{ a: 2 } } // => x = { a : 2 }
const y = { ...null } // => y = {}
Now, we can use the same idea to simplify our code:
return {
username: "rad-coder",
...(userIsBanned && {banned: true})
}
And if there are multiple conditions:
return {
username: "rad-coder",
...(userIsBanned && {banned: true}),
...(userIsOrganic && {organic: true}),
...(userIsPaid && {paid: true}),
}
"Code is Harder to Read!"
I know some folks would say that this just makes code harder to read and is needlessly clever. And maybe that's right.
I personally find it a nifty trick to avoid writing more code than that's needed, but some developers might not feel that way, which makes its usefulness subjective.
So, use it if only you think it's a good choice.
Top comments (1)
nice trick been looking for this kind of trick since a long time