Javascript
Function Parameters And Return Value
A Javascript function is used to perform a group of related tasks. It is used to perform an operation. Javascript functions are defined by the 'function' keyword followed by the name we wish to call the function and then followed by open and close parenthesis. Let us look at an example code below.<html> <head> <title> Function Parameters And Return Value In Javascript. </title> <script type="text/javascript"> function sayHelloAndHowAreYou() { document.write("Hello!<br/>"); document.write("How are you?<br/>"); } </script> </head> <body> <script type="text/javascript"> sayHelloAndHowAreYou(); </script> </body> </html>
<html> <head> <title> Function Parameters And Return Value In Javascript. </title> <script type="text/javascript"> function addTwoNumbers(number1, number2) { var sum = number1 + number2; document.write("sum is " + sum + "<br/>"); } </script> </head> <body> <script type="text/javascript"> addTwoNumbers(1,2); addTwoNumbers(10,20); </script> </body> </html>
<html> <head> <title> Function Parameters And Return Value In Javascript. </title> <script type="text/javascript"> function addTwoNumbers(number1, number2) { var sum = number1 + number2; return sum; } </script> </head> <body> <script type="text/javascript"> var sum = addTwoNumbers(1,2); document.write("sum = " + sum + "<br/>"); sum = sum + addTwoNumbers(10,20); document.write("sum = " + sum + "<br/>"); </script> </body> </html>
In the code above, we declared a function that accepts 2 parameters. The parameters are added together and then returned to the function caller. During the first function call, the it returned a value equal to 3. The value is now assigned to a variable named 'sum'. During the second function call, it returned a value of 30 and was added to the value of the variable 'sum' and is now assigned as the new value of the variable 'sum'. It is also very important to take remember that once the 'return' statement is invoked, all other code inside the function that comes after the 'return' statement will no longer be executed.