Logical OR Operator
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:||treats0,"", andfalseas falsy soscore || 'No score'will show “No score” even when the score is 0. Use??(nullish coalescing) if you want a fallback only fornullorundefined.
