Short-circuit β The Hidden Behavior of && and ||
After completing this topic
You will understand the principle behind how && and || return values other than true/false, and you will be able to utilize them in practice for conditional rendering and default value patterns.
&& and || do not return booleans
console.log("hello" && "world"); // "world"
console.log(0 || 42); // 42In other languages, && and || always return true or false. JavaScript is different. They return one of the operands directly. This is called short-circuit evaluation.
How && works
&& returns the left operand if the left side is falsy, and the right operand if the left side is truthy.
false && "hello" // false β the left is falsy, so the left is returned
"hi" && "hello" // "hello" β the left is truthy, so the right is returned
0 && "hello" // 0 β the left is falsy
"hi" && 0 // 0 β the left is truthy, so the right is returnedIf the left side is falsy, the right side is not even executed. This is where the name "short-circuit" comes from.
const user = null;
user && console.log(user.name); // The right side is not executed because user is nullHow || works
|| returns the left operand if the left side is truthy, and the right operand if the left side is falsy.
"hello" || "world" // "hello" β the left is truthy, so the left is returned
0 || 42 // 42 β the left is falsy, so the right is returned
"" || "default" // "default" β the left is falsy
null || "fallback" // "fallback"You can think of it as "returning the first truthy value."
Conditional rendering in React
One of the most common uses of && in React is for conditional rendering:
function Dashboard({ user }) {
return (
<div>
{user && <UserProfile user={user} />}
{user?.isAdmin && <AdminPanel />}
</div>
);
}If user exists, it renders <UserProfile />; otherwise, it renders nothing. This allows for conditional rendering in a single line without using an if statement.
However, there is something to be aware of:
{count && <Badge count={count} />}If count is 0? && will return 0. React will render 0. This is probably not what you intended.
{count > 0 && <Badge count={count} />}It is safer to use a boolean expression like this.
Setting default values with ||
const name = user.name || "Anonymous";
const theme = config.theme || "light";This is a common pattern for setting default values with ||. However, if you need to treat 0 or "" as valid values, use ?? instead.
Key takeaways
&&returns the left operand if it's falsy, and the right operand if it's truthy.||returns the left operand if it's truthy, and the right operand if it's falsy. When using&&for conditional rendering in React, remember to be careful with the number 0.