Course Banner


Default Parameter Values

ES6 allows function parameters to have default values.
In ECS6 Default parameters can be also used. If you use the default parameter the benefit is that even if the user does not enter the value in function, it shows the default value. 
But if the value is entered, then the default value is overwritten.

 

<!DOCTYPE html>

<html>

<body>

<h2>Default parameter in JavaScript</h2>

<div id="result"></div>

<script>

function chkFunction(x, y = 10) {

  // y is 10 if not passed or undefined

  return x + y;

}

document.getElementById("result").innerHTML = chkFunction(5);

</script>

</body>

</html>

Function Rest Parameter

When you do not know the actual number of parameters, you can use the rest parameter.  Rest parameter is used with 3 dots(...)

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Function Rest Parameter</h2>

<p id="result"></p>

<script>

function sum(...args) {

  let sum = 0;

  for (let arg of args) {

   sum += arg;

   }

     return sum;

}

let x = sum(6, 9, 34, 25, 29, 66, 77);

document.getElementById("result").innerHTML = x;

</script>

</body>

</html>