javascript function tutorial

A javascript function is a group of statements which is used for performing a specific task. We can invoke it from anywhere in our program. It provides the facility of code re-usability.

Syntax:

function functionname(parameterList) {
         //Block of statements
      }

:

<html>
 <head>
 <script type="text/javascript">
 function sayHello(){
 alert("Hello tutorialspointexamples.com");
 } 
 </script>
 </head> 
 <body> 
 <p>Hello World Javascript Example.</p>
 <form> 
 <input type="button" value="Say Hello" onclick="sayHello()"/> 
 </form> 
 </body> 
 </html>

Try it:

JS Bin on jsbin.com
 

JavaScript function with arguments example:

<html>
 <head>
 <script type="text/javascript">
 function sayHello(msg){
 alert(msg);
 } 
 </script>
 </head> 
 <body> 
 <p>Hello World Javascript Example.</p>
 <form> 
 <input type="button" value="Say Hello" 
     onclick="sayHello('Hello tutorialspointexamples.com')"/> 
 </form> 
 </body> 
 </html>

Try it:

JS Bin on jsbin.com
 

JavaScript function return value example:

<html>
 <head>
 <script type="text/javascript">
 function sayHello(msg){
 alert(getMsg());
 } 
function getMsg(){
return "Hello tutorialspointexamples.com";
 }
 </script>
 </head> 
 <body> 
 <p>Hello World Javascript Example.</p>
 <form> 
 <input type="button" value="Say Hello" onclick="sayHello()"/> 
 </form> 
 </body> 
 </html>

Try it:

JS Bin on jsbin.com