DEV Community

Marcos Henrique
Marcos Henrique

Posted on

13 3

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️