ProgramGuru

null and undefined

Learn null and undefined

JavaScript has two common absence values: null and undefined. TypeScript can make you handle them deliberately.

In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.

What you’ll learn

  • Explain the main rule behind null and undefined.
  • Predict the result of the complete runnable TypeScript example.
  • Recognize one common mistake and correct it.

Understand the concept

undefined often means a value was not supplied or a property is missing. null is commonly an explicit no-value choice. With strictNullChecks enabled, a string is not automatically interchangeable with null or undefined; use union types when an absent value is possible.

Run a complete TypeScript example

Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.

TypeScript code

const middleName: string | undefined = undefined;
 const selected: number | null = null;
 console.log(middleName ?? "(not provided)");
 console.log(selected ?? "no selection");

Verified output

(not provided)
no selection

How to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.

Trace the execution

The ?? operator uses the fallback because each left operand is nullish. The output contains two readable fallback messages.

Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.

Common mistakes and how to avoid them

Do not use a truthiness check when 0 or an empty string is a legitimate value; ?? preserves those values.

Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.

Practice it yourself

Set middleName to an empty string and selected to zero, then check that neither fallback is selected.

Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.

Check your understanding

With strictNullChecks, what type permits a string or undefined?
Choose one answer. You can try again.

Answer and explanation

string | undefined

A union explicitly includes allowed absence states.

Review the key idea

null and undefined: undefined often means a value was not supplied or a property is missing.

A union explicitly includes allowed absence states.

Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: The bigint and symbol Types →