Logical Operators (&&, ||, !) in JavaScript
JavaScript logical operators return operand values, not booleans: a && b yields a if falsy else b; a || b yields a if truthy else b. This powers idioms like config = opts || defaults and render = ready && <UI/> β but also the classic 0/"" clobbering that ?? now fixes.
Both short-circuit (right side may never evaluate β the guard pattern fn && fn()), ! always yields real boolean, and !! normalizes. Precedence (!, then &&, then ||) matches C, so the same parenthesization habits apply.
Values, not booleans
"hi" && 42 is 42; 0 || "d" is "d" β the operators select operands by truthiness.
Short-circuit guards
user && user.name never touches .name when user is nullish β evaluation stops at the decided operand.
The 0/"" trap
count || 10 and name || "anon" clobber legitimate 0/"" β ?? exists precisely to default only null/undefined.
! normalizes
!value is always boolean; !!value is the standard truthiness-to-boolean probe.
console.log("hi" && 42, 0 && 42);console.log(0 || "d", "" || "d");Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself β building beats watching.