CodeBlanks Logo Icon CodeBlanks

Optional and default params

Learn optional and default parameters.

Optional parameters

To make a parameter optional, place ? after its name. Optional parameters must come after required ones. When omitted, the value is undefined.

function selam(isim: string, unvan?: string): string {
  return (unvan || "") + " " + isim;
}

With ? a parameter becomes skippable.

Default parameters

To give a parameter a default value, write = value. If the argument is omitted or undefined, the default is used. Default parameters are automatically optional.

function selam(isim: string, unvan: string = "Bay"): string {
  return unvan + " " + isim;
}
selam("Ali");  // "Bay Ali"

A default value makes the parameter skippable.

Practice Function with a default parameter

Define a function named selam with isim: string and unvan: string = "Bay" parameters and return type string. The function should return unvan + " " + isim. Print the result of calling selam("Ali") with console.log.

Starter code

index.ts
// selam adında bir fonksiyon tanımla
// isim zorunlu dize, unvan varsayılan "Bay" ile dize olsun
// dönüş türü string, unvan + " " + isim döndürsün
// selam("Ali") sonucunu yazdır

Sample solution

index.ts
function selam(isim: string, unvan: string = "Bay"): string {
    return unvan + " " + isim;
}
console.log(selam("Ali"));

Expected output

Bay Ali

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In <code>function selam(isim: string, unvan?: string)</code>, if you call <code>selam("Ali")</code>, what is the value of <code>unvan</code>?

  • unvan is undefined Correct answer
  • The function ignores isim
  • Compile error (missing parameter)
  • unvan becomes null

Explanation: When an optional parameter is omitted, its value is <code>undefined</code>; it does not cause a compile error because it is marked optional with <code>?</code>.

2 Add the default value

Question
function selam(isim: string, unvan = ____): string { return unvan + " " + isim; }
Answer
function selam(isim: string, unvan = "Bay"): string { return unvan + " " + isim; }

Explanation: The default title must be <code>"Bay"</code>; <code>"Bayan"</code> and <code>"Hanim"</code> are wrong titles, and <code>"5"</code> is a wrong numeric content value.

3 Optional and default parameter concepts

Term Meaning
unvan?: string Optional parameter
unvan: string = "Bay" Default parameter
? (parametre adından sonra) Makes a parameter optional
= "değer" Gives a parameter a default value

All lessons in Beginner