2026-09-25 · Q&A guide

Conditional Object Inclusion in Array Declaration – JavaScript

Use spread syntax and a ternary to add an object only when a flag is true.

Why Inline Conditional Arrays Matter

When building a list of items that may or may not contain a new user, declaring the array once keeps code tidy and eliminates mutation after creation.

Core Technique – Spread + Ternary

Wrap the optional object in an array and spread it inside the main array. The ternary decides whether that array contains the object or is empty.

const arr = [
  { name: 'John', money: 45 },
  { name: 'Lui',  money: 65 },
  { name: 'Kegan', money: 100 },
  ...(isNewUser ? [{ name: 'Eric', money: 90 }] : [])
];

Handling Multiple Optional Items

If more than one optional object exists, create an array of them and spread it. Each item can be wrapped in its own ternary or filtered later.

const optional = [
  isNewUser && { name: 'Eric', money: 90 },
  isAdmin && { role: 'admin' }
].filter(Boolean);
const arr = [
  { name: 'John', money: 45 },
  ...optional
];

Practical Tips

Always ensure the ternary returns an array; otherwise the spread will throw. Using an empty array keeps the syntax consistent. This pattern works in ES6+ environments and avoids side effects.

Takeaway: Spread an array inside the declaration and use a ternary to include the new object only when needed.

People also ask

Can I use push instead of spread?

Yes, but push mutates the array after declaration, which defeats the purpose of a single‑step build.

What if I need to add multiple optional objects?

Create an array of optional items, filter out falsy values, and spread it into the main array.

Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.

← All posts