Read an Optional Property Safely
Read an Optional Property Safely
Optional chaining stops a property-access chain when the guarded value is null or undefined. Pair it with a nullish default when a missing school profile needs a readable fallback.
Before this topic, review Share Code with Modules if its terms are unfamiliar.
What you’ll learn
- Explain read an optional property safely through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The zero mark exists and survives the nullish fallback.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
const student = {};
console.log(student.profile?.marks ?? "Pending");
Expected output
PendingRun in JavaScript compiler →Recognize the important boundary
It does not catch every exception or validate fields. An undeclared root name still throws, and an optional call still needs a callable value when present.
Try a small variation
JavaScript · original source for practice
const student = {};
console.log(student.profile?.marks ?? "Pending");
Your task: Replace student = {} with student = {profile:{marks:0}}. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The zero mark exists and survives the nullish fallback.
JavaScript · complete worked variation
const student = { profile: { marks: 0 } };
console.log(student.profile?.marks ?? "Pending");
Expected output
0Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
const student = {};
console.log(student.profile?.marks ?? "Pending");
Keep the useful idea
Optional chaining stops a property-access chain when the guarded value is null or undefined. Pair it with a nullish default when a missing school profile needs a readable fallback.
Check your variation against this explanation: The zero mark exists and survives the nullish fallback.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.