Short-circuit evaluation in React.js with real-life example
Short-Circuit Evaluation in React.js
🔍 What is Short-Circuit Evaluation?
In JavaScript and React, short-circuit evaluation is a logical operation where the second expression is only evaluated if the first one is not sufficient to determine the result.
🧠 Syntax in React:
condition &&
If condition
is true, the component renders. If it's false, nothing is rendered.
🛍️ Real-Life Example: Show Discount Only If Available
const Product = ({ name, hasDiscount }) => (
{name}
{hasDiscount && 🎉 Discount available!
}
);
If hasDiscount
is true
, the message "Discount available!" will show. If false, nothing will be shown.
💡 Real World Analogy
Imagine you're going out:
- If it’s not raining → go outside
- If it’s raining → stay home
!isRaining && goOutside();
⚠️ Be Careful
If the value is 0
, ""
, or null
, it will not render:
const Cart = ({ itemCount }) => (
{itemCount && You have {itemCount} items in your cart.
}
);
If itemCount
is 0
, this won't render anything! Use conditional operators if needed.
✅ Alternative (Ternary Operator)
{itemCount === 0 ? Your cart is empty.
: You have {itemCount} items.
}
✔️ Short-circuiting is perfect for simple conditional rendering in React!