DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Marcos Henrique
Marcos Henrique

Posted on

Have you noticed that you can short-circuiting the spread operator?

WTF is short-circuiting in Programming?


Short-circuiting is where an expression is stopped being evaluated as soon as its outcome is determined.

How its work with spread operator?

Basically, we can short-circuit the spread operator using the && operator.
So, if the condition is met, the spread operator will be executed and the object's properties will be spread out. Otherwise, it will be ignored.

Let's see an example:

const isActiveOnMenu = true;

const pastaCarbonara = {
  ingredients: ['pasta', 'bacon', 'eggs', 'cheese', 'garlic'],
  price: 10.0
};

const menu = {
  ...isActiveOnMenu && pastaCarbonara
};

console.log(menu);
// { ingredients: ['pasta', 'bacon', 'eggs', 'cheese', 'garlic'], price: 10.0 }

Enter fullscreen mode Exit fullscreen mode

As you can see, in the example above, the pasta carbonara object will only get spread when the isActiveOnMenu 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.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. 🌈