JavaScript functions are used to perform operations. We can call javaScript function many times to reuse the code.
There are mainly two advantages of javaScript functions.
function functionName([arg1, arg2, ...argN]){ //code to be executed }
<script> function mssg(){ alert("Hello World! this is message"); } </script> <input type="button" onclick="mssg()" value="Say Hello"/>
To invoke a function somewhere later in the script, you would simple need to write the name of that function.
<script type="text/javascript"> function msg() { alert("Hello World !"); } </script> <input type="button" onclick="msg()" value="Message"/>
We can call function by passing parameters.
A function can take multiple parameters separated by comma.
<script> function squr(num){ alert(num*num); } </script> <form> <input type="button" value="Square" onclick="squr(3)"/> </form>
We can call function that returns a value and use it in our program.
<script type="text/javascript"> function mul(num1, num2) { var total; total = num1 + num2; return total; } </script> <script type="text/javascript"> var output; output = mul(2, 2); document.write(output); </script>
4