What is a Default Parameter in a JavaScript function?

A JavaScript function can have default parameters values. Using default function parameters, you can initialize formal parameters with default values. If you do not initialize a parameter with some value, then the default value of the parameter is undefined.

image

While calling function foo, you are not passing any parameter, so the default value of variable num1 is set to undefined. However, sometimes you may want to set a default value other than undefined. In the past, the best strategy was to test for the parameter value undefined and then assign a value. So, let us say that in the above example, you want to set the default value of num1 to 9. You can do that as shown in the code listed below:

image

ECMAScript 6 introduced default parameters for the function. Using the default parameters features of ECAMA 2015, you no longer have to check for an undefined parameter value. Now, you can put 9 as the default value in the parameter itself. You can rewrite the function above to use the default value as shown below:

image

For function foo, if num1 parameter’s value is not passed, then JavaScript will set 9 as the default value of num1.

Read full article on the Infragistics blog

Leave a comment

Create a website or blog at WordPress.com