JavaScript lesson · 18 min
JavaScript null and undefined
Understand missing values, intentional empty values, and safe fallback handling.
What you will practice
- Recognize undefined as a missing value.
- Recognize null as an intentional empty value.
- Use ?? to choose safe fallback text.
What this means
`undefined` usually means a value has not been provided or a property does not exist.
`null` usually means the program intentionally stored an empty value.
Both values often mean `nothing useful here`, but the reason can be different. Understanding that difference makes API data and form state easier to debug.
If this is your first time seeing this
`undefined` often means JavaScript could not find the value you asked for.
`null` usually means someone intentionally put an empty value there.
Mini glossary
- undefined
- A missing value, often from a property that does not exist.
- null
- An intentional empty value.
- ??
- The nullish coalescing operator, used to provide a fallback for null or undefined.
Example from everyday life
undefined is like asking for a drawer that does not exist. null is like opening a drawer and finding an empty label that says: intentionally empty.
How it works step by step
- The code creates a user object where `city` is missing and `avatarUrl` is intentionally null.
- `user.city` becomes `undefined` because the property is not there.
- `user.avatarUrl` is `null` because the property exists but has no image yet.
- `??` provides readable fallback strings for both missing values.
Where you will use this
- An API may omit optional fields, causing undefined values.
- A profile can store `avatarUrl: null` before the user uploads a picture.
- A settings form can use fallback values until the user saves preferences.
Before you run the code
Do not panic when you see `undefined`. It often means you are reading a property that does not exist.
Use clear fallbacks when missing data is normal, and show real errors when missing data means something is broken.
Common beginner mistakes
- Treating null and undefined as always identical.
- Using a missing value without checking it first.
- Using `||` as a fallback when `0` or an empty string may be valid.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Add `city: "Paris"` to the user and run again.
- Change `avatarUrl` to a real URL string.
- Try replacing `??` with `||` and compare behavior.