Menu
Coddy logo textTech

Default Parameters

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 50 of 77.

In programming, it's common to have functions where some parameters have default values. These are values that the parameter will take if no argument is provided during the function call. Default parameters make functions more flexible and easier to use.

To define a function with default parameters in JavaScript, you assign a value to the parameter in the function definition using the = operator. Here's the basic syntax:

function functionName(param1, param2 = defaultValue2, param3 = defaultValue3) {
	// Function body
	// ...
}

In this syntax, param2 and param3 have default values. If the function is called without providing arguments for these parameters, they will automatically take their default values.

Here's an example:

function greet(name, greeting = "Hello") {
	console.log(`${greeting}, ${name}!`);
}

greet("Alice"); // Output: Hello, Alice!
greet("Bob", "Hi"); // Output: Hi, Bob!

In this example, the greet function has two parameters: name and greeting. The greeting parameter has a default value of "Hello". When the function is called with only one argument, greeting takes its default value. When called with two arguments, the second argument overrides the default value.

Default parameters can be any valid expression, including numbers, strings, booleans, arrays, objects, or even the results of other function calls.

Cheat sheet

Default parameters allow functions to have preset values when no argument is provided. Use the = operator in the function definition:

function functionName(param1, param2 = defaultValue) {
	// Function body
}

Example:

function greet(name, greeting = "Hello") {
	console.log(`${greeting}, ${name}!`);
}

greet("Alice"); // Output: Hello, Alice!
greet("Bob", "Hi"); // Output: Hi, Bob!

Default parameters can be numbers, strings, booleans, arrays, objects, or function call results.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals