How to conditionally add a property to an object in JavaScript

October 30, 2023

Conditionally adding a property to an object in JavaScript can streamline object creation and ensure only relevant data is included. Engineers can achieve this with simple checks and modern JavaScript syntax to keep objects lean and maintainable.

Understand the basics of object manipulation

Objects in JavaScript are mutable, meaning properties can be added, modified, or deleted after an object is created. Here's a simple object for reference:

let user = { name: 'Alice', age: 25 };

Use the if statement for conditional addition

An if statement is the most straightforward way to conditionally add a property:

if (condition) { user.isAdult = true; }

Employ logical operators for inline conditioning

Logical operators like && (AND) can add properties without an explicit if block:

condition && (user.isAdult = true);

Take advantage of the ternary operator

The ternary operator provides a concise way to conditionally add properties:

user.status = condition ? 'active' : undefined;

Delete unwanted properties

If a property is conditionally added and later deemed unnecessary, the delete keyword helps:

if (condition) { user.tempProperty = 'tempValue'; } // Some code later delete user.tempProperty;

Use the spread operator for conditional properties

ES6 introduced the spread operator, which is handy for conditionally adding properties:

user = { ...user, ...(condition && { newProperty: 'newValue' }) };

Implement Object.assign for dynamic properties

Object.assign can also be used for conditional additions:

Object.assign(user, condition && { newProperty: 'newValue' });

Utilize functions for complex conditions

When dealing with complex conditions, a function can help keep code clean:

function addPropertyIf(condition, obj, key, value) { if (condition) { obj[key] = value; } } addPropertyIf(condition, user, 'newProperty', 'newValue');

Adopt the nullish coalescing operator for defaults

The nullish coalescing operator (??) can set default property values when a conditionally added property is null or undefined:

user.optionalProperty = someValue ?? 'default';

Consider the optional chaining operator for nested objects

For deeply nested objects, optional chaining (?.) prevents errors when conditionally adding properties to undefined nested objects:

user.settings?.theme = condition ? 'dark' : 'light';

Embrace functional programming with immutable patterns

To avoid side-effects, use immutable patterns by creating a new object each time:

user = condition ? { ...user, newProperty: 'newValue' } : { ...user };

Leverage ES2020 optional chaining with assignment

ES2020 allows for optional chaining combined with assignment to add properties only if the nested object exists:

user.profile?.(profile.bio = 'New bio');

By following these techniques, you can add properties to JavaScript objects conditionally, leading to more robust and flexible code. Whether for a simple feature toggle or a complex state-dependent structure, these patterns ensure that objects contain only the necessary data at any given time.

Ship faster, worry less with Basedash

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

Dashboards and charts

Effortlessly make charts and create a space for your team to work together towards shared goals and metrics.

User CRM

SQL composer with AI

Admin panel

Screenshot of a users table in a database. The interface is very data-dense with information.