& vs &&: The JavaScript Operator Showdown

& runs a bitwise AND on two 32-bit numbers and returns the numeric result; && performs a logical AND on two expressions and returns the last truthy operand or the first falsy one.

Dev teams often grab & when they meant && because the symbols look alike and both appear in “if” checks; the bug silently coerces values and flips logic, leaving QA puzzled at 2 a.m.

Key Differences

& is eager: it converts both sides to 32-bit integers and does bit math. && is lazy: it stops at the first falsy value and preserves the original type, making it perfect for short-circuit guards.

Which One Should You Choose?

Use && for everyday truth tests and guard clauses. Reserve & for low-level flags, masks, or performance hacks—places where you truly want to twiddle bits, not decide flow.

Examples and Daily Life

Writing user roles? `if (user.flags & 0b0010)` checks a single bit; `if (isAdmin && isActive)` keeps login smooth. Misplacing them turns “admin” into 0 or throws “true” into your mask.

Can I chain && safely in React render props?

Yes—React treats each step as a guard, returning the final node or nothing on the first falsy value.

Does & ever short-circuit?

No—both operands are always evaluated, so side effects in the second expression will still run.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *