Default Values

Contact Us or call 1-877-932-8228
Default Values

Default Values

The ECMAScript 6 ("ES2015") update to JavaScript introduced the default function parameter feature, allowing us to set default values for parameters if they are not supplied when a function is invoked. For instance, a function declared as

function fun(num=2) {
	//code here
}

could be called without a parameter:

document.write(fun());

The function's num parameter would be set to 2, since no value was supplied for the parameter in the function call. Here's another example:

Code Sample:

AdvancedFunctions/Demos/defaultParams.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Default Parameters</title>
</head>
<body>
	<h1>Default Parameters</h1>
	<script>
		function fullName(fname='First', lname='Last') {
			return fname + ' ' + lname;
		}
		document.write(fullName('Brian','Hoke'));
		document.write('<hr>');
		document.write(fullName('Brian'));
		document.write('<hr>');
		document.write(fullName());
	</script>
</body>
</html>

Code Explanation

Function fullName accepts two parameters, fname and lname, each of which is assigned a default string value.

We make three calls to the function, supplying two, one, and zero parameters, respectively. Note that, if only one actual parameter is supplied, it is passed in for the first (fname) formal parameter.

Next