Hello! Welcome to our next lesson.
In our previous session, we explored the powerful concept of functions as first-class citizens. You learned that you can pass functions as arguments (callbacks), receive them in other functions (higher-order functions), and even return them from functions (function factories). This flexibility is central to modern JavaScript.
Today, we'll add another tool to our function toolkit that makes them more robust and easier to use. We'll be looking at how to define default parameter values. This allows you to set a fallback value for a function's parameters, which is used if an argument isn't provided when the function is called. This simple feature helps prevent common errors and makes your code more predictable.
The Problem: When Arguments Go Missing
Before we see the solution, let's understand the problem. What happens when you define a function that expects arguments, but you call it without providing them?
Let's imagine a simple function to create a welcome message:
function createGreeting(name, greeting) {
return `${greeting}, ${name}!`;
}
// What happens if we forget the greeting?
const myGreeting = createGreeting("Alice");
console.log(myGreeting); // Output: undefined, Alice!
When an argument isn't passed for a parameter, JavaScript automatically assigns it the value undefined. This can lead to strange outputs, or worse, cause your program to crash if you try to perform an operation on that undefined value.
For a great visual demonstration of this problem, let's watch a short video.
JavaScript Function Default Parameters
The video 'JavaScript Function Default Parameters' by Steve Griffith clearly shows what happens when an optional parameter is undefined and you try to perform an action on it, like converting it to uppercase.
Watch from the beginning (00:00) to 02:50. Pay close attention to: The setup of the sendMessage function with an optional title parameter. What happens when the function is called without a title (it becomes undefined). The error that occurs when the code tries to run title.toUpperCase() on an undefined value.
As the video shows, trying to use a method like .toUpperCase() on an undefined value results in a TypeError, which stops your script from running.
The Solution: Default Parameter Syntax
Before the modern JavaScript syntax (ES6), developers had to manually check for undefined inside the function, like this:
// The "old" way
function createGreeting(name, greeting) {
if (greeting === undefined) {
greeting = "Hello"; // Manually assign a default
}
return `${greeting}, ${name}!`;
}
This works, but it adds extra code. Modern JavaScript provides a much cleaner way to achieve the same result directly in the function's signature.
Understanding Default Parameters in JavaScript
The article 'Understanding Default Parameters in JavaScript' from DigitalOcean provides a clear explanation of this modern syntax.
Please read the sections 'Arguments and Parameters' and 'Default Parameter Syntax'. This will recap the problem of undefined arguments and show you the clean parameter = value syntax to solve it.
So, our createGreeting function can be rewritten like this:
// The modern, clean way
function createGreeting(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
// Call without a greeting
console.log(createGreeting("Alice")); // Output: Hello, Alice!
// Call with a greeting (overrides the default)
console.log(createGreeting("Bob", "Good morning")); // Output: Good morning, Bob!
You simply use the assignment operator (=) to provide a default value right where you define the parameter.
This visual breakdown shows exactly how JavaScript decides whether to use the provided argument or the default value.

Test your understanding!
Given the following function:
function multiply(a, b = 1) {
return a * b;
}
What will be the output of the following calls?
multiply(5, 2)multiply(5)multiply(5, undefined)
Show answer
10. The provided argument2overrides the default value forb.5. No argument was provided forb, so its default value1is used (5 * 1).5. Passingundefinedexplicitly also triggers the default value, sobbecomes1.
Using Multiple Defaults and Advanced Cases
You can use default values for as many parameters as you like, and they can be any data type.
function createUser(username, theme = 'light', isAdmin = false) {
console.log(`Creating user ${username}...`);
console.log(`Theme: ${theme}`);
console.log(`Admin access: ${isAdmin}`);
}
createUser('new_user');
// Output:
// Creating user new_user...
// Theme: light
// Admin access: false
A Common "Gotcha"
What if you want to accept the default value for theme but set isAdmin to true? You can't just skip an argument like this: createUser('admin_user', , true). This will cause a syntax error.
The rule is: To use the default value for a parameter, you must either omit the argument or explicitly pass undefined.
Functions - Parameters and Arguments
Wes Bos's article on function parameters has a great section that explains this exact scenario.
Read the short section titled 'How to Fall Back on Default for Only One Parameter'. It clearly demonstrates why you need to use undefined.
So, the correct way to create an admin user with the default theme would be:
createUser('admin_user', undefined, true);
// Output:
// Creating user admin_user...
// Theme: light
// Admin access: true
Because of this, it's a common best practice to place parameters with default values at the end of the parameter list. This way, you can simply omit them without having to pass undefined.
// Better design: required parameters first
function createUser(username, isAdmin = false, theme = 'light') {
// ...
}
// Now creating an admin is cleaner
createUser('admin_user', true); // theme will default to 'light'
Let's Practice!
Time to apply what you've learned.
Exercise 1: Pizza Order
- Create a function named
orderPizza. - It should accept three parameters:
size,topping, andcrust. - Give
toppinga default value of"cheese"andcrusta default value of"thin". - The function should return a string describing the order, like:
"Ordering a large pizza with pepperoni on a thick crust." - Call the function in three different ways to test the defaults:
- With only a size (
"medium"). - With a size and a topping (
"large","mushrooms"). - With a size, a topping, and a crust (
"small","olives","stuffed").
- With only a size (
Show solution
// 1, 2, 3: Define the function with defaults
function orderPizza(size, topping = "cheese", crust = "thin") {
// 4: Return the descriptive string
return `Ordering a ${size} pizza with ${topping} on a ${crust} crust.`;
}
// 5: Call the function in various ways
const order1 = orderPizza("medium");
console.log(order1); // "Ordering a medium pizza with cheese on a thin crust."
const order2 = orderPizza("large", "mushrooms");
console.log(order2); // "Ordering a large pizza with mushrooms on a thin crust."
const order3 = orderPizza("small", "olives", "stuffed");
console.log(order3); // "Ordering a small pizza with olives on a stuffed crust."
Explanation: In the first call, both topping and crust used their default values. In the second call, topping was overridden but crust used its default. In the third call, all default values were overridden by the provided arguments.
Exercise 2: API Request Configuration
- Create a function
configureApiRequestthat simulates configuring a request to an API. - It should take three parameters in this order:
endpoint,method, andtimeout. - Set a default value for
methodto"GET"andtimeoutto5000(milliseconds). - The function should return an object that represents the configuration.
- Your goal is to configure a request to the
"/users"endpoint with atimeoutof10000, but you want to use the defaultmethod("GET"). - Call the function correctly to achieve this and log the resulting object.
Show solution
// 1, 2, 3: Define the function
function configureApiRequest(endpoint, method = "GET", timeout = 5000) {
// 4: Return the configuration object
return {
endpoint: endpoint,
method: method,
timeout: timeout
};
}
// 5 & 6: Call the function using 'undefined' to skip a default
const config = configureApiRequest("/users", undefined, 10000);
console.log(config);
/*
Output:
{
endpoint: "/users",
method: "GET",
timeout: 10000
}
*/
Explanation: To override the timeout parameter while keeping the default method, we had to explicitly pass undefined as the second argument. This signals to JavaScript to fall back to the default value for the method parameter.
Conclusion
Well done! You now know how to make your functions more resilient and flexible using default parameters. This is a feature you will use constantly as you build more complex applications.
Key Takeaways:
- Default parameters provide fallback values for function parameters when an argument is not supplied.
- They prevent errors from operations on
undefinedvalues, making code more predictable. - The syntax is simple:
function myFunc(param = defaultValue) {}. - A default is triggered if the argument is omitted or if
undefinedis passed explicitly. - It is a best practice to place parameters with default values at the end of the function's parameter list for cleaner function calls.
Next Up:
This lesson concludes our module on the fundamentals of functions. In the next module, we will begin one of the most important deep dives for your journey toward TypeScript and Next.js: Scope, Closures, and the Execution Context. You've already had a taste of these concepts, but we're about to explore exactly how JavaScript manages variables, tracks function calls, and enables powerful patterns like closures. This will be a foundational piece of your mental model for how JavaScript truly works.