DEV Community

Agney Menon
Agney Menon

Posted on • Originally published at blog.agney.dev

9 1

Conditionally spread into Object/Array - Javascript

There comes a time when we want to add more fields/elements into an array or object when it satisfies a certain condition. This blog is an exploration of how and why.

Spreading into an Array

isWinter is a boolean variable and you need to add winterEssentials if it's true and nothing otherwise.

const essentials = ['phones', 'book', 'cap'];
const winterEssentials = ['sweater', 'thermals'];

const isWinter = true;

const tripEssentials = [
  ...essentials,
  ...(isWinter ? winterEssentials : [])
];

We need an empty array at end because we cannot spread undefined or null into an array (they are not iterables). Spreading an empty array into another just keeps the array intact.

const initialArray = ['a', 'b', 'c'];
const resultingArray = [...initialArray, ...[]];
console.log(initialArray, resultingArray); // Have the same elements.

Spreading into an Object

Rest spread into object is a Stage 4 ECMA proposal and is implemented in most browsers.

It mimics the behavior of existing Object.assign operator.

const hacker = {
  hoodie: true,
}

const isHacker = true;

const person = {
  firstName: '',
  lastName: '',
  ...(isHacker && hacker)
};

console.log(person);

You will notice here that resorting to a conditional operator isn't necessary. This is because rest spread for objects tries to wrap any primitive it finds to an object.

console.log(null); // {}
console.log(undefined); // {}
console.log(0); // {}
console.log('abc') // {0: "a", 1: "b", 2: "c"}, well an array is also an object

Guide to Type Coercion in JavaScript

So the expression (isHacker && hacker) returns undefined which our spread operator converts to {} and spreading an empty array into an object results in nothing.

That's conditional spread.

PulumiUP 2025 image

From Infra to Platforms: PulumiUP 2025 Panel

Don’t miss the expert panel at PulumiUP 2025 on May 6. Learn how teams are evolving from infrastructure engineering to platform engineering—faster, more secure, and at scale.

Save Your Spot

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay