Javascript - Using Default Function Parameters

Introduction

You can pass in undefined to indicate missing parameter.

var getAnswer = function(number = 42, item = "universe") { 
    console.log(number + " is the answer to " + item); 
} 
getAnswer(undefined, "life"); // 42 is the answer to life 

Here, we are passing undefined as the first parameter, and ES6 will use the default value 42 instead.

Function default values can be any valid expression, even a function call.

You can use complex expressions as default values for parameters.

Default value expressions are evaluated lazily, meaning they're run only if a parameter's argument is not present or is undefined.

var getName = function(firstName = "Default First Name", lastName = "Default Last Name") { 
        console.log(firstName + " " + lastName); 
} 

getName("Jane"); // Jane Default Last Name 

You can access the other variables in the expression used as the default value.

var defaultName = "Default First Name"; 

var getName = function(firstName = defaultName, lastName = "Default Last Name") { 
        console.log(firstName + " " + lastName); 
} 

getName(); // Default First Name Default Last Name 

You can access a function when specifying a default for an argument.

var getFirstName = () => "Default First Name"; 

var getName = function(firstName = getFirstName(), lastName = "Default Last Name") { 
        console.log(firstName + " " + lastName); 

} 

getName(); // Default First Name Default Last Name 

If we try to check the number of arguments:

var getName = function(firstName, lastName = "Default Last Name") { 
        console.log(arguments.length); 
} 

getName("Default First Name"); // 1 

Even though the second argument gets a default value, arguments.length only returns the number of arguments passed to it.

Related Topic