How to set default parameters in ES6 ?
Function parameters with default values are initialized with default values if they contain no value or are undefined. JavaScript function parameters are defined as undefined by default. However, it may be useful to set a different default value. That is where default parameters come into play.
Syntax:
function name(parameter=value,...parameters) { }
Example 1: If we multiply two numbers in this example without passing a second parameter and without using the default parameter, the answer that this function will return is NAN(Not a Number), since if we do not pass the second parameter, the function will multiply the first number with undefined.
Javascript
function multiply(a, b) { return a * b; } let num1 = multiply(5); console.log(num1); let num2 = multiply(5, 8); console.log(num2); |
Output:
NaN 40
Example 2: If we do not pass a number as the second parameter and take the default parameter as the second parameter, it will multiply the first number with the default number, and if we pass two numbers as parameters, it will multiply the first number with the second number.
Javascript
function multiply(a, b = 2) { return a * b; } let num1 = multiply(5); console.log(num1); let num2 = multiply(5, 8); console.log(num2); |
Output:
10 40
Example 3: Default Parameter with Constructor: we can use the default parameter concept with the constructor of a class.
Javascript
class Beginner { constructor(a, b = 3) { console.log(a * b); } } let obj = new Beginner(5); let obj1 = new Beginner(5, 4); |
Output:
15 20