Skip to content
👉All tips here

How to Add Conditional Object Properties in JavaScript

Add properties in object conditionally with JavaScript

When creating objects in JavaScript, you might want to include certain properties only if specific conditions are met. This technique of adding conditional object properties in JavaScript can be achieved using the spread operator (…) along with conditional logic. Let’s explore how to master this powerful feature for more flexible and dynamic object creation.

The Problem with Static Object Properties

Picture this: you’re building a user object, and you want to add different properties based on the user’s status. Maybe they’re an admin, or they have a premium subscription or both! How do you create an object that flexibly includes or excludes properties based on these conditions?

The Solution: Conditional Spreading in JavaScript

Here’s where the magic happens. We can use the spread operator (…) combined with the logical AND operator (&&) to conditionally include properties in our JavaScript objects. This technique allows for clean and flexible object creation, adding properties dynamically based on various conditions.

Let’s break it down with an example:

const isAdmin = true;
const hasPremium = false;

const user = {
  username: 'johndoe',
  email: 'john@example.com',
  ...(isAdmin && { role: 'admin' }),
  ...(hasPremium && { subscription: 'premium' }),
  ...((isAdmin || hasPremium) && { specialFeatures: 
  ['dashboard', 'reports'] }),
};

console.log(user);
/* 
{
  "username": "johndoe",
  "email": "john@example.com",
  "role": "admin",
  "specialFeatures": [
    "dashboard",
    "reports"
  ]
}
*/

How Conditional Object Properties Work

The && expression in JavaScript is evaluated left to right. If the first expression is falsy, the full expression is short-circuit evaluated to the falsy expression (meaning the second expression is never evaluated). Here’s what’s happening in our example:

  • isAdmin && { role: 'admin' }: Since isAdmin is true, the role: 'admin' property is added to the object.
  • hasPremium && { subscription: 'premium' }: As hasPremium is false, this property is not added.
  • (isAdmin || hasPremium) && { specialFeatures: [...] }: This condition is true (because isAdmin is true), so the specialFeatures array is added.

Pro Tips for Working with Conditional Object Properties in JavaScript 🚀

  1. Order Matters: Remember, the order of your spread operations can affect the final object. Later spreads will overwrite earlier ones with the same key.
  2. Performance Considerations: While this technique is clean and readable, be mindful when using it with large objects or in performance-critical code. Each spread operation creates a new object, impacting performance if overused.
  3. Debugging Conditional Properties: When debugging, remember that falsy spreads (...false, ...null, ...undefined) are simply ignored, which might make some issues less obvious at first glance.
  4. Nullish Coalescing: For more advanced use cases, consider combining this technique with the nullish coalescing operator (??) to provide default values:
const user = {
  ...someCondition && { prop: valueIfTrue ?? defaultValue }
};

This technique allows for clean and flexible object creation, adding properties dynamically based on various conditions. It’s beneficial when dealing with complex objects that must adapt to different scenarios or user types.

So go forth and spread conditionally, my friends!

Learn more about the concepts used in conditional object properties:

Logical AND (&&): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

Spread syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax


Related post: https://front-end.tips/javascript-pro-tip-mastering-dynamic-property-names/