CodeBlanks Logo Icon CodeBlanks

Default parameters

Learn to define parameters with default values.

Default parameters

A default parameter is a fallback value used when the caller does not pass an argument. It is written after the parameter name as = value.

Syntax: function greet(name = 'Guest') { return 'Hello ' + name; }. With greet() it returns 'Hello Guest'; with greet('Ayşe') it returns 'Hello Ayşe'. The default is used only when the argument is missing or undefined.

Default parameters make function calls more robust. The caller does not have to pass every argument; where one is missing, a sensible fallback is used.

undefined and default

A default parameter kicks in only in two cases: when no argument is given, or when undefined is passed explicitly. Values like null, 0, or an empty string count as arguments; the default is not used.

Example: function f(x = 10) { return x; }. f() returns 10 (default). f(undefined) also returns 10. But f(null) returns null, because null is a deliberate value; the default does not apply.

This distinction matters: undefined means 'absent', while null means 'empty'. The default applies only in the 'absent' case.

Practice Compute the tax

Define a function tax(amount, rate = 18). Its body returns amount * rate / 100. First print the result of tax(1000) (180 with the default rate), then the result of tax(1000, 8) (80) on separate lines with console.log.

Starter code

index.js
// Define tax and print the results of two calls

Sample solution

index.js
function tax(amount, rate = 18) {
  return amount * rate / 100;
}
console.log(tax(1000));
console.log(tax(1000, 8));

Expected output

180
80

Questions and answers

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

1 When is the default used?

  • Always
  • When the argument is missing Correct answer
  • When the argument is false
  • When the argument is true

Explanation: the default kicks in only when the argument is missing or undefined.

2 Default name

Question
function greet(name = ____) { return 'Merhaba ' + name; }
Answer
function greet(name = 'Misafir') { return 'Merhaba ' + name; }

Explanation: name = 'Misafir' uses Misafir when there is no argument.

3 Match the default behaviour

Term Meaning
f() Default (empty call)
f(undefined) Default (undefined passed)
f(null) Returns null
f(5) Returns 5

All lessons in Beginner