Skip to content

JavaScript function with default parameter | Set Default Parameters example

  • by

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:

JavaScript function with default parameter

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:

JavaScript Set Default Parameters example

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:

Not default parameter values in the function declaration

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading