Topic 11 of 37
Short-Circuiting with &&
Overview
The logical AND (&&) operator evaluates expressions from left to right. It 'short-circuits' and returns the first falsy value it finds. If all values are truthy, it returns the last one. It is frequently used in React for conditional rendering without writing full if-statements.
Syntax
In the guard clause, console.log only runs if user.loggedIn is truthy.
Basic Short-Circuiting
javascript
const result = true && "Hello" && 42; // Returns 42
const falsyResult = "Hi" && 0 && "World"; // Returns 0
// Used as a guard clause
const user = { loggedIn: true, name: "Alice" };
user.loggedIn && console.log("Welcome " + user.name);Common Pitfalls
- Using && with 0 in React: `0 && <Component/>` will actually render '0' to the screen because 0 is falsy and is returned immediately.
Interview Tips
- Explain the difference between boolean returns (like in C++) and value returns (how JS && returns the actual evaluated operand).
Real-World Example
Conditional rendering in JSX (React).
example
javascript
// If isLoading is true, show the spinner. Otherwise, render nothing.
function UserProfile({ isLoading }) {
return (
<div>
{isLoading && <Spinner />}
<ProfileData />
</div>
);
}