null vs undefined
- TypeScript course
- Beginner
- Lesson 63/89
- 4 min
Learn the difference between null and undefined.
Difference between null and undefined
JavaScript and TypeScript have two distinct "no value" states. undefined means a variable has been declared but its value has not been assigned yet. null is an empty value the programmer sets on purpose.
let a: string | null = null;
let b: string | undefined = undefined;
let c: string | undefined;
console.log(c); // undefinedSo undefined means "not yet", null means "intentionally empty".
strictNullChecks
By default, TypeScript treats null and undefined as assignable to any other type. With the strictNullChecks option on, they become separate types; you cannot assign null to a string variable, but writing string | null explicitly is valid.
let s: string = "hi";
let maybe: string | null = null;This option lets you catch runtime errors at compile time.
Practice Write greet with a null check
Write a function greet(name: string | null): string. If name is null, return "yok"; otherwise return name.toUpperCase(). Print the result of both calls.
Starter code
// greet fonksiyonunu yaz
// parametre name: string veya null
// name null ise "yok" döndür
// değilse name'i büyük harfe çevirSample solution
function greet(name: string | null): string {
if (name === null) {
return "yok";
}
return name.toUpperCase();
}
console.log(greet("ada"));
console.log(greet(null));Expected output
ADA yok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the value of a variable that has been declared but not assigned?
- empty string
- undefined Correct answer
- null
- 0
Explanation: In TypeScript, a declared but unassigned variable is automatically undefined. null is a value the programmer assigns on purpose.
2 Add null to the union
let userName: string ____ = null;
let userName: string | null = null;
Explanation: A union combines types with the | operator. string | null says the value can be either string or null, allowing null assignment under strictNullChecks.
3 null and undefined parts
| Term | Meaning |
|---|---|
null |
Intentional empty value |
undefined |
Unassigned variable |
string | null |
Can be string or null |
strictNullChecks |
Makes null and undefined separate types |