JavaScript Functions
A lot of values provided in the default environment have to type function. It is a piece of program wrapped in a value. Such values can be applied in order to run the wrapped program. For example in a browser environment, the variable alert holds a function that shows a little box with a message.
Syntax of a Function
Executing a function is called invoking, calling or applying it. You can call a function by putting parentheses after an expression that produces a function value. Usually you will directly use the name of the variable that holds the function. The values between the parentheses are given to the program inside the function.
An user defined function is defined by the function keyword. The rule of giving a function name is same as the rules of variable name. The parentheses contains the parameter names separated by commas. the code which will be executed by the function is placed inside the curly braces.
Syntax:
// code to execute
}
Function with Return
The return statement should be the last statement in a function. It is used when you want to return a value from a function.
Example:
function jsFunction(par1, par2) {
return par1 + par2 ;
}
Run Example
Invoke a function
To call a function somewhere later in the code, you just need to write the name of that function.
Example:
return "This is a JavaScript function.";
}
document.write( jsFunction() );
Run Example