Skip to content
Astera Technology

Apply a function default only when the argument is undefined

Test omitted, undefined, null and empty-string arguments separately.

Download complete case notes and answer keys ↓

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.

Complete original program
function title(value='Untitled'){return value;}
console.log(JSON.stringify([title(),title(undefined),title(null),title('')]));
Exact console output
["Untitled","Untitled",null,""]
Values and execution
ArgumentDefault usedReturned value
OmittedYesUntitled
undefinedYesUntitled
nullNonull
""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.

Separate finite alternative
function title(value){return value||'Untitled';}
console.log(JSON.stringify([title(),title(undefined),title(null),title('')]));
Alternative output
["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.

Fresh boundary program
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}));
Boundary output
{"values":["Untitled","Untitled",null,""],"calls":2}

Original example files