JavaScript function

The JavaScript function is the set of reusable codes. You can call your function anywhere in your program. To remove the repetition of codes on your program you can use a function. 

JavaScript function declaration

To declare a function in your program you use the function keyword. The following syntax shows that how to declare function on javascript.

function functionName(parameters) {
    // body of function
   }
Example 1: JavaScript function with out argument(0 argument)
<script type = "text/javascript">
  
      function greeting() {
         alert("Good morning");
      }
  
</script>
Calling Functions
You can call a function by using its name as follows.
Example 2: Calling a function
<html>
    <head>
        <script type ="text/javascript">
  
            function greeting() {
               alert("Good morning");
            }
        
      </script>
    </head>
    <body>
        <p>Click the following button to call a function</p>
        <form >
            <input type="button" onclick="greeting()" value="Click me">
        </form>
    </body>
</html>
Output 

Click the following button to call a function

Function parameters
You can also pass multiple parameters while calling a function.
Example 3: function with multiple parameters(adding two numbers)
<html>
    <head>
        <script type ="text/javascript">
  
            function add(num1,num2) {
               document.write(num1+num2);
            }
        
      </script>
    </head>
    <body>
        <p>Click the following button to call a function</p>
        <form >
            <input type="button" onclick="add(15,20)" value="Click me">
        </form>
    </body>
</html>
Output 

Click the following button to call a function

Function with return value
you can also call a function that returns a value.
Example 4: function with the return value(multiplying two numbers)
<html>
   <head>  
      <script type ="text/javascript">
         function multiply(n1,n2) {
            var product;
            product = n1 * n2;
            return product;
         }
         function display() {
            var result;
            result = multiply(15, 20);
            document.getElementById("multi").innerHTML=(result);
         }
      </script>      
   </head>
   
   <body>
      <p>Click the following button to call the function</p>  
      <p id="multi"></p>    
      <form>
         <input type ="button" onclick ="display()" value ="Click me">
      </form>      
     
  </body>
</html>
Output

Click the following button to call the function