JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 9: Modern JavaScript SyntaxLesson 44 of 150About 35 minutes

Lesson 44: Nullish coalescing and default values

01Opening question

A user sets their volume to 0. Your code writes volume || 50 and the music plays at 50. What went wrong?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

|| falls back for any falsy value; ?? falls back only for null and undefined.

const volume = 0;
console.log(volume || 50);
console.log(volume ?? 50);

03Objective and prerequisites

Learning objective: Choose between ||, ?? and default parameters, and use ??= and ||= to fill in missing values without overwriting valid zeros and empty strings.

You need: Lesson 12: Logical operators, Lesson 43: Optional chaining

Skills practised: Nullish coalescing and defaults.

04Explanation

a || b returns b whenever a is falsy: false, 0, "", null, undefined or NaN.

a ?? b (nullish coalescing) returns b only when a is null or undefined. Zero, empty strings and false are kept.

Default parameters give a parameter a value when the argument is missing or undefined: function greet(name = "friend").

x ??= value assigns only if x is nullish; x ||= value assigns if x is falsy.

05Definitions

Nullish coalescing
The ?? operator, which returns its right side only when the left side is null or undefined.
Falsy
A value treated as false in a condition: false, 0, -0, 0n, "", null, undefined and NaN.
Default parameter
A value used for a parameter when its argument is undefined.
Logical assignment
The ??=, ||= and &&= operators, which assign only under a condition.

Open the full glossary

06Visual learning object

Fallback laboratory. Try 0, "", false, null and undefined on the left of || and ?? and compare the results side by side.

Loading the interactive object…

Open the full Optional chaining laboratory page with its guided experiment.

07Examples

ex-044-01|| versus ?? Browser-executable JavaScript

Only ?? keeps valid falsy values.

const values = [0, "", false, null, undefined, 7];
for (const v of values) {
  console.log(String(v), "|", v || "fallback", "|", v ?? "fallback");
}
Sample input
None
Expected output
0 | fallback | 0 | fallback | false | fallback | false null | fallback | fallback undefined | fallback | fallback 7 | 7 | 7
Common mistake
Using || for numbers where 0 is meaningful.
Try this
Add NaN to the list and predict both columns.
Source
examples/ex-044-01-or-vs-nullish.js (repository pending publication)

ex-044-02Default parameters Browser-executable JavaScript

Defaults apply when the argument is missing or undefined, not null.

function makeBadge(name, color = "blue") {
  return `${name} [${color}]`;
}
console.log(makeBadge("Ada"));
console.log(makeBadge("Grace", undefined));
console.log(makeBadge("Alan", null));
Sample input
None
Expected output
Ada [blue] Grace [blue] Alan [null]
Common mistake
Expecting null to trigger the default.
Try this
Make null fall back too by using color ?? "blue" inside.
Source
examples/ex-044-02-default-params.js (repository pending publication)

ex-044-03Fill in missing values Browser-executable JavaScript

??= assigns only when the value is nullish.

const config = { retries: 0, timeout: null };
config.retries ??= 3;
config.timeout ??= 5000;
config.label ||= "default";
console.log(config);
Sample input
None
Expected output
{retries: 0, timeout: 5000, label: "default"}
Common mistake
Using ||= on retries, which would replace the intentional 0.
Try this
Change retries to ||= and see what happens.
Source
examples/ex-044-03-logical-assignment.js (repository pending publication)

ex-044-04Defaults can use earlier parameters Browser-executable JavaScript

Each default is evaluated when the function is called.

function range(start, end = start + 3, step = 1) {
  const out = [];
  for (let i = start; i < end; i += step) out.push(i);
  return out;
}
console.log(range(2));
console.log(range(0, 10, 4));
Sample input
None
Expected output
[2, 3, 4] [0, 4, 8]
Common mistake
Referring to a later parameter in a default, which throws a ReferenceError.
Try this
Call range(5, undefined, 2).
Source
examples/ex-044-04-defaults-refer.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Keep a zero quantity

Replace || with ?? where 0 is valid.

const item = { name: "Pen", qty: 0 };
const qty = item.qty || 1;
console.log(`${item.name} x${qty}`);

Greeting with defaults

Use default parameters.

function greet(name, greeting) {
  return `${greeting}, ${name}!`;
}
console.log(greet("Ada"));
console.log(greet("Linus", "Hei"));

Normalise options

Fill in missing options without overwriting valid falsy values.

// Write normalizeOptions(options = {})

09Prediction

Commit to an answer first, then run the real code to compare.

let a = 0;
let b = 0;
a ||= 5;
b ??= 5;
console.log(a, b);

What is printed?

10Debugging investigation

Free shipping gets charged

Some products have a shipping cost of 0, but checkout charges the standard 4.99 for them.

const product = { name: "Ebook", shipping: 0 };
function shippingFor(p) {
  return p.shipping || 4.99;
}
const cost = shippingFor(product);
console.log(`${product.name} shipping: ${cost}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

User preferences

A media player stores volume, playback speed and captions. A volume of 0 and captions turned off are real choices, so the code uses ?? to fill only settings the user never chose.

const saved = { volume: 0, captions: false };
const volume = saved.volume ?? 50;
const speed = saved.speed ?? 1;
console.log(volume, speed, saved.captions ?? true);

12Knowledge check

1. What is printed?

console.log(0 ?? 10);
  • 0
  • 10
  • undefined
  • null

2. What is printed?

console.log("" || "none");
  • ""
  • none
  • undefined
  • An empty line

3. Which argument makes a default parameter apply?

  • null
  • 0
  • undefined
  • false

4. Why is this a SyntaxError?

const a = null, b = 0, c = 1;
console.log(a || b ?? c);
  • ?? cannot be mixed with || without parentheses
  • a is undefined
  • c is reserved
  • ?? needs a semicolon

5. What is printed?

const o = { n: 0 };
o.n ??= 1;
console.log(o);
  • {n: 0}
  • {n: 1}
  • {}
  • An error

6. A discount of 0% is valid. Which line is correct?

  • const d = input.discount || 10;
  • const d = input.discount ?? 10;
  • const d = input.discount && 10;
  • const d = !input.discount ? 10 : 0;

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Keep a zero quantity: Prints Pen x0; Uses ??
  • Greeting with defaults: Prints both; No arguments
  • Normalise options: Prints the options; No argument; Keeps true
  • ex-044-01: output matches the documented expected output
  • ex-044-02: output matches the documented expected output
  • ex-044-03: output matches the documented expected output
  • ex-044-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-09-modern-javascript-syntax/lesson-044-nullish-coalescing-and-default-values/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • || replaces any falsy value.
  • ?? replaces only null and undefined.
  • Default parameters apply for undefined arguments.
  • ??= and ||= fill in values conditionally.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation nullish coalescing and default values
Context: I am learning nullish coalescing and default values in JavaScript.
Task: Explain || versus ?? and default parameters using a settings example with zeros and empty strings.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction nullish coalescing and default values drill
Context: I have practised nullish coalescing and default values.
Task: Give me six snippets mixing ||, ??, ??= and defaults and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging nullish coalescing and default values bug
Context: My setting of 0 keeps being replaced by the default value.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation nullish coalescing and default values practice
Context: I finished the nullish coalescing and default values exercises.
Task: Create three exercises that normalise options objects.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review nullish coalescing and default values review
Context: Here is my code that uses nullish coalescing and default values.
Task: Review my code for || fallbacks that should be ?? and for defaults that miss null.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.