What is default parameters in js

In this post we'll going to learn default parameters with 2 examples

The concept of default parameter a new feature introduced in the ES6 version of JavaScript.

🔗What is default parameters ?

Default parameters are basically parameters that a function can depend as a backup if parameters are not specifically declared or pass through to the function when we call

Syntax:-

js
function fnName(param1 = defaultValue1, ..., paramN = defaultValueN) { ... }

🔗Example 1:

Passing Parameter as Default Values

js
sum = (a, b) => a + b;
console.log(sum(4, 7)); // 11
console.log(sum(4)); // NaN

In the above example, if no value is provided for b when sum is called, b's value would be undefined when evaluating a + b and sum would return NaN

Passing Parameter as Default Values

To avoid this we can use default parameters in below example the default value of b is 3

js
sum = (a, b = 3) => a + b;
console.log(sum(4, 7)); // 11
console.log(sum(4)); // 7
default parameters

🔗Example 2 :

We can also pass function Value as default value

js
const sum = () => 15;
const calculate = (x, y = x * sum()) => {
return x + y;
};
const result = calculate(10);
console.log(result); // 160
function Value as default value

Explanation :-

  • 10 is passed to the calculate() function. ( x = 10 )
  • x becomes 10, and y becomes 150 ( y = x sum() = 10 15 = 150 )
  • The result will be 160 ( result = ( x + y = 10 + 150 ) = 160 )

🔗QUIZ time

What is the output of following code comment below 💬

js
sum = (x = 3, y = 5) => {
return x + y;
};
console.log(sum(2, 10));
console.log(sum(5));
console.log(sum());

Output comment below

js
// option :
// 12 , 10 , 8
// 8 , 8 , 8
// 8 , 10 , undefined
// undefined 5 , undefined