DEV Community

Cover image for JS πŸ”₯: Conditionally setting an object property
Benjamin Mock
Benjamin Mock

Posted on β€’ Originally published at codesnacks.net

25 4

JS πŸ”₯: Conditionally setting an object property

Want to get better at Web Development πŸš€πŸš€πŸš€? Subscribe to my weekly newsletter at https://codesnacks.net/subscribe/


Let's assume we only want to add an object property if some condition is true. We can do this using an if-statement of course:

const someCondition = true;
const anotherCondition = false;
const myObject = {
  name: "codesnacks",
};

if(someCondition){
  myObject.author = "Ben";
}

if(anotherCondition){
  myObject.platform = "dev.to";
}

console.log(myObject); // {name: "codesnacks", author: "Ben"}

We can achieve the same using the object spread operator ( ...) in combination with the condition when creating the object. No additional if-statement is needed. This is especially elegant if an object has multiple conditional properties.

const someCondition = true;
const anotherCondition = false;
const myObject = {
  name: "codesnacks",
  ...(someCondition && { author: "Ben" }),
  ...(anotherCondition && { platform: "dev.to" }),
};

console.log(myObject); // {name: "codesnacks", author: "Ben"}

Want to get better at Web Development?
πŸš€πŸš€πŸš€subscribe to the Tutorial Tuesday βœ‰οΈnewsletter

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more β†’

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

AWS Industries LIVE!

AWS Industries LIVE! features AWS Partners discussing various topics related to their industry, their solutions, and how they can help customers.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️