JS Tip of the Day: Default Function Parameters

Default Function Parameters
Version: ES2015
Level: Beginner

Functions in JavaScript can be called with any number of arguments, whether or not they expect them. If a function parameter does not have a respective argument, it will appear in that function as undefined.

function logValues (a, b) {
    console.log(a);
    console.log(b);
}

logValues(1); // 1, undefined

If you want a parameter to have a specific value if the function is called without that respective argument, you can specify a default parameter value. To define a default parameter add an assignment expression in the parameter list of the function for that parameter. If the parameter were to have an undefined value, it would instead be assigned to the default parameter value.

function logValues (a, b = 2) { // b's default parameter value is 2
    console.log(a);
    console.log(b);
}

logValues(1); // 1, 2

More info:

1 Like