Functions in JavaScript
- JavaScript function is collection of JavaScript Statements , that are grouped together and enclosed within Opening Curly and Closing Curly braces.
- JavaScript function can be called using different methods.
- JavaScript Function Can return a value.
JavaScript Function Can be placed -
- Inside Head Section
- Inside Body Section
- Inside External File having (.js) extension.
Note :
JavaScript Function must be loaded before calling it , so we must write JavaScript function inside <head> and </head> section
JavaScript Function can be called by -
- Automatically when Page gets loaded completely
- Can be invoked by any JavaScript Event.
How to declare a function ?
function FunctionName(var1,var2,...,varX) { some code }
Explanation :
- function keyword is used to write definition of function.
- Parameters can be passed to JS function separated by comma.
- Code included inside “Opening Curly” and “Closing Curly“.
- “return” statement is used to return value from function.
Live Example :
<html> <head> <script type="text/javascript"> function print() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Call Function" onclick="print()" /> </form> </body> </html>
Output :
Download JS Function Example : Click Here