Modern JavaScript
About Lesson

In this JavaScript lesson we are going to talk about JavaScript Default Parameters, It is used for adding default values to function parameters if no value or undefined is passed. also it is JavaScript ES6 feature.



For example we have a function that takes two parameters, if you see this code you will receive 11 in the output.



But what if we just add one parameter, if you see our function expects two parameters, if we give one parameter you will receive NaN in the output.


To solve this problem we can use ES6 default parameters, let’s take a look at this example.


In this example for the second parameters we have added a default value, now if we add just one value, there will be no problem, because it will take the default parameter as second value.



This is the second example and we have used multiple default parameters.



JavaScript Default Parameters Features


We already have talked that Default function parameters is feature in JavaScript that allows developers to specify default values for function parameters. If value for parameter is not passed when the function is called, the default value is used instead. these are some features JavaScript Default Parameters along with commented code examples:


  1. Single Default Parameter: Default values can be set for individual parameters in a function.

In this example name parameter is assigned default value of Guest. If the function is called without passing an argument for name, the default value is used.


  1. Multiple Default Parameters: Multiple parameters can have default values set in function.

In this example tax and discount parameters are assigned default values of 0.1 and 0. If the function is called without passing an argument for tax or discount, the default values are used.



  1. Default Parameters Can Use Previous Parameters: Default values can be based on the values of previous parameters.

In this example, the isStudent parameter is assigned default value based on the value of the age parameter.


In result we can say that default function parameters can make functions more flexible and easier to use, especially in situations where not all parameters are required or need to be specified every time the function is called.