Conditional spread operator

2019, Aug 29

JavaScript Object — Add member conditionally using spread operator

You might have faced situations where you needed to create JavaScript object on basis of some condition. I had such situations where I needed to create user object and add a flag “isVerified”: true if the user’s email is verified. How we can do that:

const isEmailVerified = () => true; //or false
const userData = {
  name: "John",
  email: "john@email.com"
};
const userObject = {
  id: 1,
  ...userData
};if (isEmailVerified) {
    userObject.isVerified = true;
}
console.log(userObject);

console

As you can see, here email is verified. Condition is passing and it is adding key “isVerified” to userObject. If email will not be verified then it will not add this “isVerified” key. Code is looking fine but….

expression

With ES6 feature we can write it in better way. Yes, I am talking about spread operator. Let’s write above code more beautifully with spread syntax and short-circuit evaluation.

const isEmailVerified = () => true; //or false
const userData = {
  name: "John",  email: "john@email.com"

};
const userObject = {
  id: 1,
  ...userData,
  ...(isEmailVerified() && {isVerified: true})
};
console.log(userObject);

console-1

We are getting same result by writing less code in better way.

Giffy

Conclusion

In above example, spread syntax allow me to get rid of if statement. I think, it makes the code more cleaner.