Outline

When we declare a function that takes parameters, we generally want the developer (ourselves or someone else) to pass those parameters in. Most of the time, that happens as expected. But sometimes people may forget to pass a parameter in, or maybe you want to allow them to call the function without passing in the parameter and you'll provide a default value. Default parameters for functions is perfect for this use case. Here's how you can provide a default parameter to a function:

function divide(top, bottom = 1) {
  return top / bottom;
}

This divide function expects two parameters, top and bottom. The = 1 after the bottom parameter means that if nothing is passed into the function as the bottom parameter, its value will be 1 instead of undefined. So if we call the function like this:

const result = divide(4);

The result will be 4 instead of NaN, which is a special value in JavaScript that means not a number. Default parameters are easy to implement and can be a way to prevent errors in our code from forgetting to pass all the arguments into a function.

You can learn more about default parameters in this blog post.

 

I finished! On to the next chapter