Optional and default parameters
Concept and syntax
An optional parameter uses ? and may be omitted; its value can be undefined. A default initializer is used for an omitted or explicitly undefined argument, not for null. A defaulted parameter is optional at the call site when trailing. Distinguish the caller contract from the initialized value inside the function.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function label(text:string, count=1, suffix?:string){return text.repeat(count)+(suffix ?? "");}console.log(label("a"),label("b",undefined,"!"),JSON.stringify(label("c",0)));Expected output:
a b! ""The first call repeats a once. In the second call undefined activates the default and the suffix adds !. The final call explicitly supplies zero, so the JSON representation of its result is "".
Common mistake
Intentionally invalid; compile separately and do not execute.
function label(text:string, suffix?:string){ return text+suffix.toUpperCase(); }Expected diagnostic: TS18048. The optional suffix might be absent. Use a default or guard before accessing it.
Practice and recap
Call label with zero, omitted count and explicit undefined.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Optional and default parameters — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function label(text:string, count=1, suffix?:string){return text.repeat(count)+(suffix ?? "");}console.log(label("a"),label("b",undefined,"!"),JSON.stringify(label("c",0)));Which diagnostic and explanation match the rejected example under the lesson settings?
function label(text:string, suffix?:string){ return text+suffix.toUpperCase(); }