React / React Conditionals / Logical OR Operator
Home /React /React Conditionals /Logical OR Operator

Logical OR Operator

💻 React 1 min read

Logical OR Operator ||

The logical OR operator (||) returns the right-hand side when the left-hand side is falsy (false, null, undefined, 0, “”, NaN). It is used for fallback rendering  show value A, but if A is falsy, show B instead.
function UserProfile({ user }) {
  return (
    <div>
      {/* Show user name, or fallback to 'Anonymous' */}
      <h2>{user.name || 'Anonymous User'}</h2>

      {/* Show bio or placeholder text */}
      <p>{user.bio || 'No bio provided yet.'}</p>

      {/* Show avatar or default image */}
      <img
        src={user.avatar || '/images/default-avatar.png'}
        alt="Profile"
      />

      {/* Show role or 'Student' as default */}
      <span>Role: {user.role || 'Student'}</span>
    </div>
  );
}
Beware of 0 and Empty String: || treats 0, "", and false as falsy  so score || 'No score' will show “No score” even when the score is 0. Use ?? (nullish coalescing) if you want a fallback only for null or undefined.