Adding a default parameter value to a function in JavaScript

OpenJavaScript 0
Reading Time: < 1 minute 🕑

Last updated: June 28, 2022.

You can add a default parameter value to a function so that if no value is passed in as an argument, the default value will be used:

function logName(username = "Captain Anonymous") {
    console.log(username);
}

logName("Mickey Mouse"); // Mickey Mouse

logName(); // Captain Anonymous

If an argument is passed in when the function is called, the default value will be ignored and the argument value used.

When is this useful?

In the right circumstances, setting a default parameter value is a useful way of ensuring that a function has the necessary inputs to complete properly.

For example, if you were creating a tip calculator, you may assume a tipping rate of 15 percent, unless otherwise specified.

You could achieve this by setting a default parameter value for the function:

function tipCalulator(total, percent = 0.15) {
    const tip = total*percent;
    return total + tip;
}

tipCalulator(100); // 115

tipCalulator(100, 0.20); // 120

By setting a default value, a suggested tip amount is always generated.