Logical and nullish operators
Overview
Logical operators let you combine and reverse conditions.
const loggedIn = true;
const isAdmin = false;
loggedIn && isAdmin; // false — both must be true
loggedIn || isAdmin; // true — at least one is true
!loggedIn; // falseWith booleans, they follow simple truth tables:
a |
b |
a && b |
a || b |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
! (NOT) flips any value to the opposite boolean: !true is false, !0 is true, !'hello' is false. Two of them, !!value, convert a value to its boolean equivalent.
Short-circuiting
&& and || stop as soon as they know the answer, and they return one of their operands — not always a boolean:
const name = '' || 'Anonymous'; // 'Anonymous'
const ready = user && user.ready; // undefined if there is no usera && b— ifais falsy, the answer must be falsy, so it returnsawithout looking atb. Otherwise it returnsb.a || b— ifais truthy, the answer must be truthy, so it returnsawithout looking atb. Otherwise it returnsb.
“Without looking” really means b is never evaluated. If b is a function call, it doesn’t run:
isLoggedIn && showDashboard(); // only calls showDashboard when logged in
cache || loadFromServer(); // only loads when there's no cacheThis is a common shorthand, though an if statement is often clearer for actions.
Precedence
! binds tightest, then &&, then ||. So a || b && c means a || (b && c). When you mix them, add brackets:
if (isAdmin || (isOwner && !isLocked)) { … }Default values with ||
Because || returns the first truthy value, it was the traditional way to provide defaults:
function greet(name) {
name = name || 'friend';
return `Hello, ${name}!`;
}That works until a falsy value is legitimate.
Nullish coalescing: ??
|| falls back on any falsy value, including 0 and ''. That’s often wrong:
const volume = 0;
volume || 50; // 50 — oops, 0 was a real value
volume ?? 50; // 0 — ?? only replaces null or undefined?? (“nullish coalescing”) returns the right side only when the left side is null or undefined — the two values that mean “nothing here”. Compare them side by side:
Value of x |
x || 'default' |
x ?? 'default' |
|---|---|---|
undefined |
'default' |
'default' |
null |
'default' |
'default' |
0 |
'default' |
0 |
'' |
'default' |
'' |
false |
'default' |
false |
'hello' |
'hello' |
'hello' |
Use ?? for settings and numbers where 0, '' or false are valid answers. Use || when any empty-looking value should be replaced — like the empty nickname in this topic’s exercise.
You can’t mix
??with&&or||without brackets.a ?? b || cis a syntax error; write(a ?? b) || c.
Optional chaining: ?.
Reading a property of undefined or null throws an error. ?. returns undefined instead:
const user = { profile: null };
user.profile.photo; // TypeError: Cannot read properties of null
user.profile?.photo; // undefined
user.settings?.theme ?? 'light'; // 'light'?. checks the value on its left. If that is null or undefined, the whole chain stops and gives undefined; otherwise it carries on as normal. You can use it at several points in a long chain:
const city = order?.customer?.address?.city;It also works for method calls (obj.method?.()) and indexes (list?.[0]):
callbacks.onSave?.(); // calls onSave only if it exists
const first = results?.[0]; // undefined if results is missingDon’t overuse
?.. If a value should always exist, let the error happen — it points you straight to a bug. Use?.where missing values are expected, such as optional settings or data from an API.
Logical assignment
Three operators combine a logical check with assignment:
options.size ??= 'medium'; // set only if size is null/undefined
user.name ||= 'Anonymous'; // set only if name is falsy
cart.discount &&= 0.1; // set only if discount is already truthy??= is the most useful: it fills in missing settings without overwriting values that were set on purpose — even falsy ones like 0.
const settings = { volume: 0 };
settings.volume ??= 50; // stays 0
settings.theme ??= 'dark'; // addedSafe display name
Return the user’s nickname if set, otherwise their first name, otherwise 'Guest'. user itself may be undefined. An empty-string nickname should count as “not set”.
function displayName(user) {
// your code here
}
displayName({ nickname: 'Ash', firstName: 'Asha' }); // 'Ash'
displayName({ nickname: '', firstName: 'Asha' }); // 'Asha'
displayName(undefined); // 'Guest'function displayName(user) {
return user?.nickname || user?.firstName || 'Guest';
}Summary
&&needs both sides true;||needs either;!flips a value.&&and||short-circuit and return one of their operands, not always a boolean.??falls back only fornullorundefined, unlike||, which falls back for any falsy value.?.stops and returnsundefinedinstead of throwing on a missing value.||=,&&=and??=assign only when needed.