Beginner · 9 min
Missing values and defaults
Handle null and undefined without replacing valid zero or empty-string values.
Use a nullish default
?? uses its right-hand value only when the left side is null or undefined. It preserves values such as 0, false, and an empty string.
const saved = null;
console.log(saved ?? "Guest");
console.log(0 ?? 10);Output
Guest 0
Read an optional property
?. stops a property access when the value before it is null or undefined. Combine it with ?? to choose a default.
const user = { name: "Mina" };
console.log(user.address?.city ?? "Not provided");Output
Not provided
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Keep a valid zero
Set quantity to savedQuantity unless it is null or undefined. Preserve the saved zero and display quantity.
Use ?? instead of ||.