Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Conditionally spreading objects in JavaScript

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

For example, you can do something like this.

const obj = {
    a: 1,
    b: 2,
    c: 3
};

const newObj = {
    ...obj
};

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.

I recently learned about a neat trick to do this in JavaScript. So, let’s see how we can do this.

Short-circuiting the spread operator

Essentially, we can short-circuit the spread operator using the && operator. So, if the condition is met, the spread operator will be executed and the properties of the object will be spread. Otherwise, it will be skipped.

Here’s an example.

const isActive = true;

const user = {
  name: "Amit",
  age: 30
};

const activeUsers = {
  ...isActive && user
};

console.log(activeUsers);
// { name: 'Amit', age: 30 }

As you can tell, in the example above, the user object will only get “spread” when the isActive is true and since logical AND (&&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.

There’s one caveat though. 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.

And that’s how you can conditionally spread objects in JavaScript!

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?