Mark As Completed Discussion

Default Parameters

Default parameters allow us to provide fallback values for function parameters in case no value or undefined is passed when the function is called.

Syntax

To define a default parameter, we can assign a value directly to the function parameter in the function declaration.

JAVASCRIPT
1function functionName(parameter = defaultValue) {
2  // function logic
3}

Examples

Let's take a look at some examples of using default parameters:

Example 1:

JAVASCRIPT
1function greet(name = 'friend') {
2  console.log(`Hello, ${name}!`);
3}
4
5// Output: Hello, friend!

Example 2:

JAVASCRIPT
1function multiply(a, b = 1) {
2  return a * b;
3}
4
5// Output: multiply(5) => 5

Example 3:

JAVASCRIPT
1function fetchUserData(username, timeout = 5000) {
2  // logic to fetch user data
3}
4
5// Output: fetchUserData('john_doe')

Example 4:

JAVASCRIPT
1function calculateArea(radius = 1) {
2  return Math.PI * radius * radius;
3}
4
5// Output: calculateArea()

Example 5:

JAVASCRIPT
1class Rectangle {
2  constructor(width = 1, height = 1) {
3    this.width = width;
4    this.height = height;
5  }
6}
7
8// Output: new Rectangle()

Example 6:

JAVASCRIPT
1const getHeroes = (team = 'Lakers') => {
2  // logic to get list of heroes
3};
4
5// Output: getHeroes()
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment