Logical and nullish operators

Topic 5 of 5 in Operators & control flow7 min readBeginnerFree course

Overview

Logical operators let you combine and reverse conditions.

JavaScript
const loggedIn = true;
const isAdmin = false;

loggedIn && isAdmin;  // false — both must be true
loggedIn || isAdmin;  // true  — at least one is true
!loggedIn;            // false

With 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:

JavaScript
const name = '' || 'Anonymous'; // 'Anonymous'
const ready = user && user.ready; // undefined if there is no user

Three flowcharts. a && b: if a is truthy return b, otherwise return a — so 0 && ‘x’ gives 0. a || b: if a is truthy return a, otherwise return b — so 0 || 50 gives 50. a ?? b: if a is null or undefined return b, otherwise return a — so 0 ?? 50 gives 0.

  • a && b — if a is falsy, the answer must be falsy, so it returns a without looking at b. Otherwise it returns b.
  • a || b — if a is truthy, the answer must be truthy, so it returns a without looking at b. Otherwise it returns b.

“Without looking” really means b is never evaluated. If b is a function call, it doesn’t run:

JavaScript
isLoggedIn && showDashboard(); // only calls showDashboard when logged in
cache || loadFromServer();     // only loads when there's no cache

This 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:

JavaScript
if (isAdmin || (isOwner && !isLocked)) { … }

Default values with ||

Because || returns the first truthy value, it was the traditional way to provide defaults:

JavaScript
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:

JavaScript
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 || c is a syntax error; write (a ?? b) || c.

Optional chaining: ?.

Reading a property of undefined or null throws an error. ?. returns undefined instead:

JavaScript
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:

JavaScript
const city = order?.customer?.address?.city;

It also works for method calls (obj.method?.()) and indexes (list?.[0]):

JavaScript
callbacks.onSave?.();       // calls onSave only if it exists
const first = results?.[0]; // undefined if results is missing

Don’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:

JavaScript
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.

JavaScript
const settings = { volume: 0 };
settings.volume ??= 50;  // stays 0
settings.theme ??= 'dark'; // added
Exercise

Safe 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”.

JavaScript
function displayName(user) {
  // your code here
}

displayName({ nickname: 'Ash', firstName: 'Asha' }); // 'Ash'
displayName({ nickname: '', firstName: 'Asha' });    // 'Asha'
displayName(undefined);                              // '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 for null or undefined, unlike ||, which falls back for any falsy value.
  • ?. stops and returns undefined instead of throwing on a missing value.
  • ||=, &&= and ??= assign only when needed.