We've built functions that take parameters and return results. But what if we wanted to make an argument optional.
Engagement Message
What if a parameter could have a "backup" or default value if we don't provide one?
In JavaScript, we can give parameters default values! When defining a function, you assign a value to a parameter using =
. If someone calls the function without providing that argument, the function uses your default instead.
Engagement Message
What do you think the default value used here is?
Now we can call this function in two ways. We can provide our own argument, or we can skip it and let the function use its default value.
Engagement Message
See how the same function handles both situations?
Functions can mix required parameters with optional ones. A common rule is to place parameters with default values at the end of the parameter list.
Engagement Message
Why do you think it's helpful to list optional parameters last?
Default parameters make functions more flexible. Users can provide just the essential information and get sensible defaults for everything else. This is especially useful for complex functions with many settings.
