Applying defaults to function parameters - Exercise

Contact Us or call 1-877-932-8228
Applying defaults to function parameters - Exercise

Applying defaults to function parameters

Duration: 5 to 15 minutes.

Here we will revisit an earlier example and use the default operator to handle optional parameters.

  1. Open AdvancedTechniques/Exercises/sumAll-defaults.html for editing.
  2. Edit the existing sumValues() to use the default operator instead of the if blocks.

Code Sample:

AdvancedTechniques/Exercises/sumAll-defaults.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Sum all numbers, default operator</title>
<script type="text/javascript">		
	function sumValues(val1, val2, val3) {
		if (val1 === undefined) {
			val1 = 0;
		}
		
		if (val2 === undefined) {
			val2 = 0;
		}
		
		if (val3 === undefined) {
			val3 = 0;
		}
		
		return val1 + val2 + val3;
	}
	
	var result1 = sumValues(3, 5, 6, 2, 7);
	var result2 = sumValues(12, 20);
	
	alert(result1);
	alert(result2);		
</script>
</head>
<body>
<p>Nothing to show here.</p>	
</body>
</html>

Solution:

AdvancedTechniques/Solutions/sumAll-defaults.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Sum all numbers, default operator</title>
<script type="text/javascript">
	function sumValues(val1, val2, val3) {
		val1 = val1 || 0;
		val2 = val2 || 0;
		val3 = val3 || 0;
		
		return val1 + val2 + val3;
	}
	
	var result1 = sumValues(3, 5, 6, 2, 7);
	var result2 = sumValues(12, 20);
	
	alert(result1);
	alert(result2);	
</script>
</head>
<body>
<p>Nothing to show here.</p>	
</body>
</html>
Next