DEV Community

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

// { 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)