Have you noticed that you can short-circuiting the spread operator?
Marcos Henrique
Posted on September 23, 2022
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 }
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.
Posted on September 23, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
April 26, 2024
September 23, 2022