In JavaScript, if you want to populate an object with some properties from another object, you can use the spread operator ... to do so.


_11
_const_ obj = {
_11
a: 1,
_11
b: 2,
_11
c: 3
_11
};
_11
_11
_const_ newObj = {
_11
...obj
_11
};
_11
_11
console.log(newObj);// { a: 1, b: 2, c: 3 }

But what if you want to conditionally spread the properties of an object? For example, you want to spread the properties of an object only if a certain condition is met.

Short-circuiting the spread operator

#

To shorten the spread operator, we can use the && operator. If the condition is met, the object properties will be spread. Otherwise, it will be skipped.

Look at this example:


_10
const isActive = true;
_10
const user = { name: "Amit", age: 30};
_10
const activeUsers = { ...isActive && user};
_10
_10
console.log(activeUsers);// { name: 'Amit', age: 30 }

Stay ahead of the pack 🐶

Join the newsletter to get the latest articles and expert advice directly to your inbox.
Totally free, no spam and you can unsubscribe anytime you want!

  • Expert Tips
  • No Spam
  • Latest Updates

I'll never share any of your information with a third party. That's a promise.

In the example above, the user object only receives "spread" if isActive is true. The logical && evaluates the operands from left to right, and returns immediately with the value of the first falsy operand it encounters. If all values are truthy, the value of the last operand is returned.

But beware! The first operand must be a boolean value. So, if you want to use a variable as the first operand, you have to convert it to a boolean value using, let’s say, the Boolean() function.


_10
_10
const user = { name: "Amit", age: 30};
_10
const isActive = Boolean(user.name);
_10
const activeUsers = { ...isActive && user};
_10
_10
console.log(activeUsers);// { name: 'Amit', age: 30 }

Thanks alot for your feedback!

The insights you share really help me with improving the quality of the content here.

If there's anything you would like to add, please send a message to:

[email protected]

Was this article this helpful?

D is for danny

About the author

Danny Engineering

A software engineer with a strong belief in human-centric design and driven by a deep empathy for users. Combining the latest technology with human values to build a better, more connected world.

Gobacktothetop

Made with 🥰 in 🏴󠁧󠁢󠁥󠁮󠁧󠁿

©2025 All rights reserved.