JavaScript also uses the functions same way as other programming languages. Functions reduce the code length due to its reusability for doing the repeated tasks. Functions remain silent until they are called or referenced by any event.
You can create functions in the head section of HTML page. In JavaScript function can be declared by using function keyword along with its name and code block wrapped within curly brackets to be executed when the function is called upon.
JavaScript Function Syntax
function functionName()
{
Code block to be executed;
}
Example of function in JavaScript
<script
language="javascript"
type="text/javascript">
function messageBox()
{
alert('Hello World!!');
}
</script>
<input
type="button"
value="clickMe"
onclick="messageBox();" />
There are 3 types of functions in JavaScript:
1. Function with return value.
2. Function with arguments
3. Function with multiple arguments that return a value.
Function that returns a value
function returnValue()
{
return ('Hello World!!');
}
Function with multiple arguments that return a value
function getProduct(arg1,arg2)
{
var n=(arg1*arg2);
return n;
}
Continue to next tutorial: Javascript Convert to Number function to learn how to convert the JavaScript object into number value.