This post will discuss how to set a default parameter for a JavaScript function.

If no value is passed to a JavaScript function, the parameter defaults to undefined and might result in undefined behavior. You can handle this with the default parameters, which lets you assign default values for a function parameter.

1. Using default parameters

With ECMAScript 2015, the default parameters were introduced in JavaScript. The default parameters allow parameters to be initialized with default values when no value is passed to a function.

In the following example, the default value of a parameter y is used when no value is specified, or an undefined value is passed.

Download  Run Code

2. Set parameter values in function body

Another solution is to check the parameter values in the function body and assign a value if they are undefined. This is demonstrated below, where no value is provided for a parameter, and checks are done within the function body to set the default value.

Download  Run Code

That’s all about setting a default parameter for a JavaScript function.