CodeBlanks Logo Icon CodeBlanks

Summary - null & undefined

Write a user profile program with safe access.

Summary - Safe profile program

You can write safe profile programs by combining optional chaining and nullish coalescing. First safely access the property with ?., then provide a default value with ??.

interface Profile { name: string; address?: { city?: string }; }
function cityOf(p: Profile): string {
  return p.address?.city ?? "bilinmiyor";
}

If address is missing or city is missing, the result is automatically "bilinmiyor"; the app never crashes.

Practice Write a safe profile program

Define a Profile interface: name: string and an optional address. The address is an object that contains an optional city: string. Write a function findCity(p: Profile): string: if address and city exist, return the city; otherwise return "bilinmiyor". Call it with two examples and print the results.

Starter code

index.ts
// Profile arayüzü tanımla: name ve isteğe bağlı address
// address bir nesnedir, içinde isteğe bağlı city bulunur
// findCity(p: Profile): string döndürür
// p.address ve p.address.city için güvenli erişim kullan
// city yoksa "bilinmiyor" döndür

Sample solution

index.ts
interface Profile {
  name: string;
  address?: { city?: string };
}

function findCity(p: Profile): string {
  return p.address?.city ?? "bilinmiyor";
}

console.log(findCity({ name: "Ada", address: { city: "Bursa" } }));
console.log(findCity({ name: "Bob" }));

Expected output

Bursa
bilinmiyor

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does p.address?.city ?? "bilinmiyor" return when address is undefined?

index.ts
interface Profile { name: string; address?: { city?: string }; }
const p: Profile = { name: "Ada" };
console.log(p.address?.city ?? "bilinmiyor");
  • returns undefined
  • throws an error
  • returns "bilinmiyor" Correct answer
  • returns null

Explanation: First, optional chaining short-circuits because address is undefined, returning undefined. Then the ?? operator sees undefined and takes the right side.

2 Complete the chain and the default

Question
const city = p.address?.city ____ "bilinmiyor";
Answer
const city = p.address?.city ?? "bilinmiyor";

Explanation: To provide a default when address or city is null/undefined, you need ??. || is wrong because it also replaces valid values like 0 or empty string; since city is a string here, that is a risk.

3 Combined model parts

Term Meaning
?. Safe property access
?? Default value
null Intentional empty value
undefined Unassigned variable

All lessons in Beginner