3 Example(s) of JavaScript function


Description :

JavaScript multiplication function is used to multiply 2 variable in the below example. 

function multiplication(a, b) { return a * b; }

How to call JavaScript function?

multiplication(4, 3) will result to 12.


JavaScript function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
<p id="sample"></p>

<script>
function multiplication(a, b) {
    return a * b;
}
document.getElementById("sample").innerHTML = multiplication(4, 3);
</script>
</body>
</html>

Output

Description :

In this example, We will pass parameter to JavaScript function and print the result based on parameter value passed. Here is the method: function greetings(f) { var message = ""; if(f == 1) message = "Good morning"; else if(f == 2) message = "bye bye"; return message; } See the code snippet:


JavaScript function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>  
 <body>
<p id="sample"></p>

<script>
function greetings(f) {
   var message = "";
   if(f == 1)
    message = "Good morning";
  else if(f == 2)
    message = "bye bye";
    
    return message;
}
document.getElementById("sample").innerHTML = greetings(1);
</script>

</body>
</html>

Output

Description :

One more example of JavaScript function with parameters, the function will return "Michael is 29 years old." and we are passing Michael and 29 as parameter value. See the code snippet:


JavaScript function Example - 3
<!DOCTYPE html>
<html>
   <head>
   <title>Welcome to LearnKode - A code learning platform</title>
   
        </head>
   <body>
      <p>Click the following button to call the function</p>
               <input type="button" onclick="sayHello('Michael', 29)" value="Say Hello">
       <script>
         function sayHello(name, age)
         {
            document.write (name + " is " + age + " years old.");
         }
      </script>
      </body>
</html>

Output