<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.");
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.