The concept of default parameters is a new feature introduced in the ES6 version of JavaScript. This allows us to give default values to function parameters. Let's take an example,
In the above example, the default value of x is 3 and the default value of y is 5.
sum(5, 15)- When both arguments are passed,xtakes 5 andytakes 15.sum(7)- When 7 is passed to thesum()function,xtakes 7 andytakes default value 5.sum()- When no argument is passed to the sum() function,xtakes default value 3 andytakes default value 5.
Using Expressions as Default Values
It is also possible to provide expressions as default values.
Example 1: Passing Parameter as Default Values
In the above program,
- The default value of
xis 1 - The default value of
yis set toxparameter - The default value of
zis the sum ofxandy
If you reference the parameter that has not been initialized yet, you will get an error. For example,
Output
ReferenceError: Cannot access 'y' before initialization
Example 2: Passing Function Value as Default Value
In the above program,
- 10 is passed to the
calculate()function. xbecomes10, andybecomes150(the sum function returns15).- The result will be
160.
Passing undefined Value
In JavaScript, when you pass undefined to a default parameter function, the function takes the default value. For example,