WEEK 5: LESSON 2 Return a Value

by Lucille Kenney

HTML

<h3>Open the Javascript console to see the output from this code</h3>
<p>Notice that I perform some <i>input validation</i> on line 2 to confirm that the function actually did receive two numbers as arguments before I add them. </p>
<p>In this case, my validation rule is that "if there are not two numeric arguments, don't do anything and return <code>null</code>.  I might code this differently if the valdiation rule was, say, "try to convert all parameters to numbers, and return the sum of those that are numeric."  </p>
<p>Be sure to read the comments in the Javascript code and the console for more information. </p>

JavaScript

function addNumbers(num1, num2){
	if (typeof num1 == 'number' && typeof num2 == 'number'){
		return num1 + num2;
	}else{
		return null;
	}
}
// call  my function and assign it to a variable
var sum = addNumbers(2, 5);

//addNumbers returns a value that can be substituted into any expression as that value
console.log ("my sum is " + 7);
console.log ("my sum is also " + sum);
console.log("and my sum is also " + addNumbers(2, 5) + ". Notice that addNumbers() returns a value that can be substituted right into an expression as a value.");