Emmanuel Akinfulubi

JavaScriptBasic

Nullish coalescing (??) vs OR (||) in JavaScript

Intermediate · 4 min read

Filling in a default is one of the most common lines of code you will write: "use the setting the user chose, or 14 seats if they didn't choose". For years JavaScript developers wrote this with ||. It works most of the time, and it quietly breaks when the user's choice is 0, an empty string or false. The newer ?? operator was added to fix exactly that.

In this tutorial you will fill in missing settings with both operators and test them against a seat count of zero, an empty note, a null tier and an air-conditioning flag set to false. Then you will use ??= to fill gaps in place, and see why mixing ?? with || is not allowed. You need to know what objects, true and false are.

Falsy values

When JavaScript uses a value as a yes/no, six values count as "no": 0, '' (empty text), false, NaN, null and undefined. These are called falsy. Everything else is truthy.

Two different questions

  • a || b asks "is a falsy?" If so, it gives b. Otherwise, a.
  • a ?? b asks "is a missing, meaning null or undefined?" If so, it gives b. Otherwise, a.

?? is called the nullish coalescing operator. "Nullish" just means null or undefined. When you are filling in a default, "is it missing?" is almost always the question you mean.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

98 Nullish or falsy: ?? against ||

fair

Fill in missing settings with defaults. Try || and ?? against a seat count of zero, an empty note, a null tier and an air-conditioning flag of false, and decide which is right for each.

Stuck? Three hints, smallest first
  1. 1. || replaces anything falsy: 0, '', false, NaN, null, undefined.
  2. 2. ?? replaces only null and undefined.
  3. 3. ??= assigns only when the current value is nullish.

Step 1: a seat count of zero

Step 1

const settings = { seats: 0, note: '', tier: null, ac: false };
console.log(settings.seats || 14); // 14
console.log(settings.seats ?? 14); // 0

The shuttle really has 0 seats left. || sees a falsy 0 and throws it away. ?? sees a real number, not null or undefined, and keeps it.

Step 2: an empty note

Step 2

const settings = { seats: 0, note: '', tier: null, ac: false };
console.log(settings.note || 'none'); // none
console.log(settings.note ?? 'none'); // (an empty string)

The second line gives '', an empty string, so nothing visible prints. Whether an empty note should become 'none' depends on what you're building. If the user cleared the note on purpose, ?? respects that.

Step 3: a null tier

Step 3

const settings = { seats: 0, note: '', tier: null, ac: false };
console.log(settings.tier || 'economy'); // economy
console.log(settings.tier ?? 'economy'); // economy

Here both agree. null is falsy and nullish, so both operators replace it. This is the case they were both made for.

Step 4: air conditioning switched off

Step 4

const settings = { seats: 0, note: '', tier: null, ac: false };
console.log(settings.ac || true); // true
console.log(settings.ac ?? true); // false

The customer turned the air conditioning off. With ||, false is falsy, so they get it back on. With ??, false is a real answer, and it stays. Any yes/no setting with a default of true has this bug when written with ||.

Step 5: ??= fills a gap in place

a ??= b means "if a is null or undefined, set it to b". Otherwise it leaves a alone:

Step 5

const trip = { fare: 0 };
trip.fare ??= 200_00;
trip.tier ??= 'economy';
console.log(trip); // { fare: 0, tier: 'economy' }

Fares are in kobo, and 200_00 is 20,000 kobo, ₦200; the underscore only helps you read it. The fare was already 0, which is not nullish, so it stayed. The tier was missing, so it was filled in. This is handy for completing an options object.

Step 6: you can't mix ?? with || unbracketed

Step 6

try {
  new Function('return null ?? true || false;');
} catch (err) {
  console.log(err.name); // SyntaxError
}

new Function('...') turns text into a function without running it, which lets the snippet show a syntax error without stopping the whole file. null ?? true || false isn't allowed, because it isn't obvious which operator should go first. Instead of guessing, JavaScript refuses and makes you write brackets: (null ?? true) || false or null ?? (true || false).

So when is || right?

When any falsy value really should count as "nothing". A search box is a good example: an empty string means "no filter", so query || 'all' is exactly what you want. Pick the operator by asking: is 0, '' or false a real answer here? If yes, use ??.

The full solution

The answer panel fills each setting with both operators, uses ??= on a trip, and shows the SyntaxError from mixing ?? with ||. Press Run to see the output.

The answer

const settings = { seats: 0, note: '', tier: null, ac: false };

const trip = { fare: 0 };
trip.fare ??= 200_00;         // already 0, which is not nullish, so it stays
trip.tier ??= 'economy';      // missing, so it is filled in

// Mixing ?? with || or && without brackets is a syntax error. new Function
// parses without running, which is how that can be shown without stopping here.
let mixing = '';
try {
  new Function('return null ?? true || false;');
} catch (err) {
  mixing = err.name;
}

console.log('seats:', settings.seats || 14, 'vs', settings.seats ?? 14);
console.log('trip after ??=:', trip);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('|| throws away a real zero', settings.seats || 14, 14);
test('?? keeps it', settings.seats ?? 14, 0);
test('|| throws away an empty note', settings.note || 'none', 'none');
test('?? keeps that too', settings.note ?? 'none', '');
test('both replace null, which is what they are for', [settings.tier || 'economy', settings.tier ?? 'economy'], ['economy', 'economy']);
test('?? keeps a deliberate false where || would not', settings.ac ?? true, false);
test('??= leaves a zero alone', trip.fare, 0);
test('but fills in a missing key', trip.tier, 'economy');
test('mixing ?? with || unbracketed is a syntax error', mixing, 'SyntaxError');

|| asks "is this falsy?", and 0, '' and false are all falsy while being perfectly good answers. A shuttle with 0 seats becomes 14, an empty note becomes 'none', and a customer who turned the air conditioning off gets it back on. ?? asks the narrower question — "is this null or undefined?" — which is almost always the question you meant when filling in a default.

|| is still right when any falsy value should be treated as absent, such as a search box whose empty string means "no filter". ??= is the assignment form and is handy for filling gaps in an options object in place. The syntax error is deliberate on the language's part: a ?? b || c has no obvious precedence, so instead of guessing, the parser refuses and makes you write the brackets.

Common mistakes

  • Using || for numeric defaults. A real 0 gets replaced. Use ??.
  • Using || for yes/no settings that default to true. A deliberate false comes back as true.
  • Mixing ?? with || or && without brackets. It's a syntax error. Add brackets to show which goes first.

Try it yourself

  1. Write withDefaults(s) that returns { seats: s.seats ?? 14, note: s.note ?? '', ac: s.ac ?? true }, and call it with {} and with settings.
  2. Predict, then check: NaN || 5, NaN ?? 5, undefined ?? null ?? 'x'.
  3. Use ??= to give every key in { a: null, b: 0, c: undefined } the value 1 only if it is missing.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.