# Applying defaults to function parameters - Exercise

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.

2. Edit the existing sumValues() to use the default operator instead of the if blocks.

## Code Sample:

<!DOCTYPE HTML>
<html>
<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);

</script>
<body>
<p>Nothing to show here.</p>
</body>
</html>

## Solution:

<!DOCTYPE HTML>
<html>
<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);