Code highlights logo

Learn

Functions

Default Parameters

To define a default parameter in a function, we use the assignment operator (=) to assign a default value to the parameter within the function declaration. The default value is used when no argument is provided or when an undefined argument is passed.

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

Examples

Let's go through a few examples to understand how default parameters work:

Example 1: Simple Default Parameter

1function greet(name = "Guest") {
2 console.log(`Hello, ${name}!`);
3}
4
5greet(); // Output: Hello, Guest!
6greet("John"); // Output: Hello, John!

In this example, we define a function greet with a default parameter name set to "Guest". When no argument is passed to the function, it uses the default value and greets the guest. If an argument is provided, it uses the provided name.


Instructions

1.

Modify the greet function to include a default parameter for name. The default value should be "stranger".

2.

Call the greet function without passing any arguments.

Sign up to start coding

Already have an account?

Sign In

Course content