Chapter 12
JavaScript null and undefined
null and undefined can both represent missing or unavailable values, but they have different meanings.
01 • Learn
What is JavaScript null and undefined?
- undefined commonly means that a value has not been assigned.
- null can be used intentionally to represent an empty or absent value.
- Both values should be handled carefully in application logic.
- The typeof operator returns 'undefined' for an undefined value.
02 • Syntax
Syntax
let value; let selectedCourse = null; console.log(value); console.log(selectedCourse);
03 • Example
Example
Try understanding this code before running it.
let studentName;
let selectedCourse = null;
console.log(studentName);
console.log(selectedCourse);
if (studentName === undefined) {
console.log('Name is not assigned');
}
04 • Remember
Important Points
- undefined and null are semantically different.
- Strict comparison such as === is useful for clear checks.
- Missing API data and optional values may need null or undefined checks.
05 • Avoid
Common Mistakes
- Assuming null and undefined are always identical.
- Calling a method on a value without checking whether it exists.
- Relying on loose equality without understanding its behavior.
06 • Practical
Real-World Use
Database fields, API responses, optional form fields, and application state can contain null or undefined values.
07 • Practice
Practice Exercise
Practice: null and undefined
Create one undefined variable and one null variable. Display both values and their typeof results.
Ready to write code?
Open the JavaScript editor and run your code with live output.