Changes

Jump to: navigation, search

Understanding JavaScript Functions

1,696 bytes added, 18:57, 24 April 2007
Returning a Value from a Function
The ''return'' statement is used to return a value from a function and the assignment (=) value is used to accept that ''return'' value at the point that the function is called.
As an exaqmpleexample, we will declare a function that adds together two arguments and returns the result: <pre> <html><head><title>A Simple JavaScript Function Example</title><script language="JavaScript" type="text/javascript"> function addValues( value1, value2){ return value1 + value2;}</script></head> <script language="JavaScript" type="text/javascript">var result = addValues( 10, 20)document.write ( "Result = " + result);</script> </body></html> </pre> The above example passes 10 and 20 through to the addValues function. The addValues function adds these two values together and returns the result. The assigment assigns the result to the variable ''result'' which is then used to construct a srting that is written to the HTML page. The function call can be made in many different places. For example we do not need to assign result to a variable, we can use diretly as an argument to the document.write call: <pre> <html><head><title>A Simple JavaScript Function Example</title><script language="JavaScript" type="text/javascript"> function addValues( value1, value2){ return value1 + value2;}</script></head> <script language="JavaScript" type="text/javascript">document.write ( "Result = " + addValues( 10, 20));</script> </body></html> </pre> Functions can also be used in conditional expressions. For example: <pre>  <html><head><title>A Simple JavaScript Function Example</title><script language="JavaScript" type="text/javascript"> function addValues( value1, value2){ return value1 + value2;}</script></head> <script language="JavaScript" type="text/javascript"> if (addValues( 10, 20) > 20){ document.write ( "Result > 20");}else{ document.write ( "Result < 20");}</script> </body></html></pre>

Navigation menu