JavaScript Functions


JavaScript functions are used to perform operations. We can call javaScript function many times to reuse the code.

Advantage of javaScript function

There are mainly two advantages of javaScript functions.

  • Code reusability: We can call a function several times so it save coding.
  • Less coding: It makes our program compact. We donít need to write many lines of code each time to perform a common task.

Syntax

function functionName([arg1, arg2, ...argN]){  
 //code to be executed  
}  

Example

<script>  
function mssg(){  
alert("Hello World! this is message");  
}  
</script>  
<input type="button" onclick="mssg()" value="Say Hello"/>
Output


Calling a Function

To invoke a function somewhere later in the script, you would simple need to write the name of that function.

Example

<script type="text/javascript">
function msg()
{
alert("Hello World !");
}
</script>
<input type="button" onclick="msg()" value="Message"/>
Output

Function Parameters

We can call function by passing parameters.

A function can take multiple parameters separated by comma.

Example

<script>
function squr(num){  
alert(num*num);  
}  
</script> 
<form> 
<input type="button" value="Square" onclick="squr(3)"/>  
</form>  
Output
  

Function with Return Value

We can call function that returns a value and use it in our program.

Example

<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>
Output
4

Share this article on