Summary - Boolean logic
Write a safe user profile fetcher using short-circuit, nullish and optional chaining.
Summary - Boolean logic
In this group you learned all the tools of boolean logic. You started with boolean values (true/false) and comparisons. You saw that short-circuit makes && and || return values.
Then you learned nullish coalescing (??) for null/undefined defaults, optional chaining (?.) for safe access, and logical assignment (&&=, ||=, ??=) for short updates. Now you will combine them in a user profile function.
Exercise Safe user profile
Define a function called getUserCity. It takes a user parameter. Inside, write const city = user?.address?.city ?? "Unknown" and return it with return city.
Show example solution
function getUserCity(user) {
const city = user?.address?.city ?? "Unknown";
return city;
}
Exercise Safely update preferences
Set prefs to { lang: null, notifications: 0 }. Write prefs.lang ??= "en". Write prefs.notifications ||= 5. Print prefs.
Show example solution
const prefs = { lang: null, notifications: 0 };
prefs.lang ??= "en";
prefs.notifications ||= 5;
console.log(prefs);
Test yourself
-
Match operator to purpose
- ?.
- safe access
- ??
- null/undefined default
- ||=
- assigns when falsy
- &&
- guard
-
Safe access operator
const user = null; const name = user____.name ?? "Anonymous"; console.log(name);Show answer
const user = null; const name = user?..name ?? "Anonymous"; console.log(name);