A JavaScript function is a code block that performs a task or calculates a value. A function can be called anywhere from your code and as many times as needed, allowing for code re-usability.
To create a function, first write the keyword function, followed by the name of the function. This is then followed by a group of comma separated parameters enclosed by parentheses - ( and ). Two curly braces { and } then follow, which contain code that the function will execute.
function functionname (param1, param2, ....) {
//Function's code goes here
}
Following example shows a function with no parameters.
function Hello () {
alert("Hello World");
}
Following example shows a function that accepts two parameters.
function Add (value1, value2) {
alert(value1 + value2);
}
To call a function you will just write the function name and pass any values, if needed.
In the following example, we create a function called Add. Then we call the function by writing the function name and passing values to it.
function Add (value1, value2) {
document.write(value1 + value2);
}
Add(2,3);
document.write("<br>");
Add(8,1);
The above example will have the below output:
5 9
Following example has a button which when clicked, calls the HelloWorld function and then shows an alert box displaying "Hello World!".
<html>
<head>
<script type="text/javascript">
function HelloWorld() {
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Hello World!" onclick="HelloWorld();" >
</form>
</body>
</html>
Below is the output of above code: