HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link name="favicon" type="image/x-icon" href="https://skillzam.com/uploads/system/e353194f3b7cd1b75d69c3ab88041985.png" rel="shortcut icon" />
<title>Default Params</title>
</head>
<body>
<!--
Default parameters : allows named parameters to be initialized with default values, if no value or undefined is passed.
-->
<h1>Demo: Default Params</h1>
<div>
<h2>Default Params</h2>
<p id="para1"></p>
</div>
<div>
<h2>Expressions as Default params</h2>
<p id="para2"></p>
</div>
<div>
<h2>Passing function value as Default params</h2>
<p id="para3"></p>
</div>
<!-- JavaScript code Starts here -->
<script>
/************************************************/
// Default Params : New way of defining the default parameters
// Example : Finding the factorial of a number
//
function findFactorial (number = 5) {
let fact = 1;
for (i = 1; i <= number; i++) {
fact *= i;
}
document.getElementById('para1').innerHTML =
`The factorial of ${number} is ${fact}.`;
}
findFactorial(); // Function invoking without argument
/************************************************/
// Expressions as Default params
// Example : squaring numbers
//
function sqNum (x = 2, y = x**2) {
document.getElementById('para2').innerHTML =
`The square of ${x} is ${y}.`;
}
sqNum(); // Function invoking without argument
/************************************************/
// Passing function value as Default param
//
const add = () => 10;
// function add() as param
const doMath = function( a, b = a + add() ) {
return a + b;
}
const mathResult = doMath(20); // Only one argument is passed instead two
document.getElementById('para3').innerHTML =
`Math Result = ${mathResult}`;
</script>
<!-- JavaScript code Ends here -->
</body>
</html>