Skip to content

JavaScript function default value

  • by

Setting up JavaScript function parameters default value is allowed to initialize variables with default values if no values or undefined are passed into the function.

Default parameters allow us to initialize functions with default values.

Simple example code of Set a default parameter value for a JavaScript function.

function say(message='Hello') {
    console.log(message);
}

say(); // 'Hello'

Example of set function default value JavaScript

In JavaScript, you can call a function without parameters.

So you can add default values like this:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   //your code
}

In the example, we set the default value of A and B as 10 and 20. If you pass the value then it will show in the alert box, otherwise, it will show 10 and 20.

Complete code

<!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);
	}
	//testing
	func();

	
	</script>

</body>
</html>

Output:

JavaScript function default value

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
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