DEV Community

Cover image for Simpler Way To Conditionally Add Properties to Javascript Object
Shubham Jain
Shubham Jain

Posted on • Updated on

Simpler Way To Conditionally Add Properties to Javascript Object

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
Enter fullscreen mode Exit fullscreen mode

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 = {}
Enter fullscreen mode Exit fullscreen mode

Now, we can use the same idea to simplify our code:

return {
   username: "rad-coder",
   ...(userIsBanned && {banned: true})
}
Enter fullscreen mode Exit fullscreen mode

And if there are multiple conditions:

return {
   username: "rad-coder",
   ...(userIsBanned && {banned: true}),
   ...(userIsOrganic && {organic: true}),
   ...(userIsPaid && {paid: true}),
}
Enter fullscreen mode Exit fullscreen mode

"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)

Collapse
 
zohaib546 profile image
Zohaib Ashraf

nice trick been looking for this kind of trick since a long time