Default Parameters

Often times, we want to write a function with a default argument. For example, you have a function that returns the square inches of a piece of wood. Most of our boards are an inch think, but occasionally they are more. Thickness in this function would default to 1. To write this function in a way that sets thickness to 1, we used to need to say:

function calculateSquareInches(width, length, thickness){
    if (thickness === undefined){
        thickness = 1;
    }
    return width * length * thickness;
}

In this example, we have an entire if block to see if a value for thickness was passed through and to assign it to it's default if it wasn't.

But now we can write:

function calculateSquareInches(width, length, thickness = 1){
    return width * length * thickness;
}

It only assigns thickness to 1 if a third parameter wasn't passed through. Be sure to write all defaults as the last arguments when defining your functions.