Another function of a function is to return a value. Imagine we have the following function:
<HTML>
<HEAD>
<TITLE>IGNOU </TITLE>
<SCRIPT Language = "JavaScript">
function calculate(a,b,c)
{
d = (a+b) * c;
return d;
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT Language = "JavaScript">
var x = calculate(4,5,9);
var y = calculate((x/3),3,5);
alert('calculate(4,5,9) = ' +x + ' and ' + ' calculate((x/3),3,5) = ' + y);
</SCRIPT>
</BODY>
</HTML>
Figure: Using a Function that Returns a Value
The function illustrated in Figure calculates a number from the numbers you pass to it. While this is done it returns the result of the calculation. The function passes the result back to the function which called it. While the function executes return statement, control goes back to the calling program without executing any more code in function, if there is any.
The calling of the function is done via the following two statements in the figure:
var x = calculate(4,5,9);
var y = calculate((x/3),3,5);
This means that you have declared variable x and are telling JavaScript to execute calculate ( ) along the arguments 4, 5 & 9 and to put the returned value (81) in x. After that you declare a variable y and execute calculate ( ) again. The first argument is x/3, which means 81/3 = 27, thus y becomes 150.Certainly you can also return strings or even Boolean values (true or false). While using JavaScript in forms, you can write a function which returns either false or true and therefore tells the browser whether to submit form or not.