Optional Properties
👨💼 Excellent! You've handled optional data safely.
🦉 Key techniques for optional properties:
- Optional chaining (
?.) - Returnsundefinedif property is missing - Nullish coalescing (
??) - Provides a default value - Type narrowing - Check with
ifbefore using
// These are all safe ways to handle optional properties:
user.bio?.toUpperCase() // undefined if no bio
user.bio ?? 'Default bio' // 'Default bio' if no bio
if (user.bio) {
console.log(user.bio)
} // Only runs if bio exists
Optional properties are essential for modeling real-world data where not every
field is always present.