Have a look at the simple function below which prints a sample line of text in the document.
2) It denotes the function name and argument list. The empty parenthesis denotes that the function does not take any parameters. In our case, the function name is
<head> tag of the html so that the function will be available all over the html document. Means, one can use this function anywhere in the html’s body.
4) In the
<body> tag, we call the function. This will print a line of text in the html browser window.
5) Shows the output of the function call in the browser window.
Below is the code:
1) The function here accepts two parameters. Note, there is no type specified here and hence the parameter can be a string or a number.
2) The body of the function adds the two numbers
N2 and prints the result in the browser’s window via
3) This is the calling code. Here, we call the function
4) We pass two numbers 10, 4 as arguments. The arguments are comma separated list enclosed within the parenthesis.
5) Shows the result of calling function with parameters.
A function can also return a value to the caller. To return a value to the calling code, one should use the returnstatement. Below is the example:
1) Shows a function which takes two numbers as parameters and adds them. The added result is in the variable
2) Here the return statement is returning the value in the variable N3. Means, it returns the addition of the two input parameters.
3) The calling code is making call to the function
SumGet by passing the arguments 3, 3. The variable
N1 holds the returned result.
4) We make a call to the
AddNumbers, which was written in the previous section. First param is the variable
5) We call
SumGet as a second parameter and the
SumGet return value is passed as a second parameter to the
Executing the code will print the result as 16.
5. Code Reference
//Sample 01: Simple Function
document.writeln("Hello From a Function </br>");
//Sample 03: Function with Parameter
function AddNumbers(N1, N2)
N3 = N1 + N2;
document.writeln("Added Result is : " + N3 + "</br>");
//Sample 05: Function with Return Value
function SumGet(N1, N2)
N3 = N1 + N2;
//Sample 02: Call the Function
document.writeln("Calling Function SimplePrint() </br>");
//Sample 04: Add Two Numbers
document.writeln("Calling Function AddNumbers(10,4) </br>");
//Sample 06: Add Two Numbers
document.writeln("Calling Function with return Value </br>");
N1 = SumGet(3,3);
document.writeln("Added Result " + AddNumbers(N1, SumGet(7,3)));