Trace the fixed program
The title function supplies Untitled only for an omitted or undefined argument. Treat null and empty text as explicit inputs in this exercise.
function title(value='Untitled'){return value;}
console.log(JSON.stringify([title(),title(undefined),title(null),title('')]));
["Untitled","Untitled",null,""]| Argument | Default used | Returned value |
|---|---|---|
| Omitted | Yes | Untitled |
| undefined | Yes | Untitled |
| null | No | null |
| "" | No | "" |
Explain the result
The initializer runs at call time when the parameter value is undefined. It does not test all falsy values. Nullish coalescing and || have different replacement boundaries, so choose the rule before choosing the operator.
Test the alternative
Using value || Untitled also replaces null and deliberate empty text. This alternative overwrites all four supplied cases.
function title(value){return value||'Untitled';}
console.log(JSON.stringify([title(),title(undefined),title(null),title('')]));
["Untitled","Untitled","Untitled","Untitled"]Work the boundary case
If producing the default increments a counter, how many times does it run for the four original calls?
Show the worked answer
Two: omitted and undefined. The initializer does not run for null or empty text.
let calls=0;function fallback(){calls++;return 'Untitled';}function title(value=fallback()){return value;}
const values=[title(),title(undefined),title(null),title('')];
console.log(JSON.stringify({values,calls}));
{"values":["Untitled","Untitled",null,""],"calls":2}