Assign a default value to the parameter is called a function with the default parameter in JavaScript. A default value is required if no value or undefined is a passed-in function.
JavaScript function with default parameter Example
Let see HTML example code of How to set default parameters in JS function.
Default value for b is 1, will use this value if no value passed for it.
<!DOCTYPE html>
<html>
<body>
<script>
function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5, 2));
console.log(multiply(5));
</script>
</body>
</html>
Output:
Another way to set default values
In JavaScript, you can call a function (even if it has parameters) without argument.
<!DOCTYPE html>
<html>
<body>
<script>
function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;
alert("A: "+a+"\nB: "+b);
}
// Test cases
func();
func(2);
func(5,2);
</script>
</body>
</html>
Output:
Q: What will happen if no value passed for the parameter and no default value set?
Answer: If a function in JavaScript is called with any missing arguments the missing values are set to undefined.
<script>
function multiply(a, b) {
console.log(a, b);
return a * b;
}
console.log(multiply(5));
</script>
Output:
Do comment if you have any doubts and suggestion on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version