JS Return Values
“return” can return a value to the caller.
1 |
function function-name (var arg) { return value } |
To call a function, use "function-name (argument);"
1 |
function-name (argument); |
Ex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<html> <head> <title>JavaScript Test</title> </head> <body> <script language="javascript"> function add(num1,num2) { return num1+num2; // pass the result value to caller } alert("3 + 5 = " + add(3, 5)); // caller </script> </body> </html> |
Output
3+5=8
Explanation:
“add( 3, 5)” means that it calls the function add (num1,num2){ }, and pass the argument “3,5” to var num1 and num2.
“return num1+num2” returns the result to caller “add(3,5)”, you can treat it as “add(3,5)= return num1+num2”, assigning the value to add(3,5).
Namely add (3,5) = 8.”alert(“3 + 5 = ” + add( 3, 5));” will show the result.