JavaScript Functions



A functions is a set of statements or a block of code.It is executed when it is called or by an event.
A function can be reused in the script as many times as you wish.
We use inbuilt functions or methods of JavaScript such as alert(),prompt(),document.write() etc.
These functions are written in Core JS and used by us.

Use of Function In JavaScript

We use function to prevent the browser from executing script at the time of page load.
With the help of a function we can execute script after an event occurs such as onclick,onhover,onfocus etc.
Function can be run in two ways:

  • With the help of event such as onclick,onfocus.
  • From another function

Creating a Function

Apart from using the built in functions in JavaScript we can also create our own functions.
To create a function type funcion followed by the name you wish for your function and then the parenthesis "()".
These parenthesis include the parameters of your function.
Here is an example.

<html>
<head>
<script type="text/javascript">
 {
  Type your code here
 }
</script>
</head>
</html>

Function With No Parameters

We can pass various number of arguments in the parenthesis of a function.Arguments are variables,
either numbers or strings, with which the function is supposed to do something.
But to begin with we will leave it blank for now.Have a look:

<html>
<head>
<script type="text/javascript">
function Show()
 {
  alert("Hello JavaScript");
 } 
</script>
</head>
<body>
<form>
<input type="button" value="First Function" onclick="Show()"/>
</form>
</body>
</html>





Click on the button.

Function with Parameters

In the above example we left the parenthesis of Show() function blank.Now we will learn what are the
different arguments or parameters we can pass in it.

<html>
<head>
<script type="text/javascript">
function Display(name,age)
 {
  alert("My name is "+name+" and age is "+age);
 } 
</script>
</head>
<body>
<form>
<input type="button" value="Show Function" onclick="Display('Harry Potter',18)"/>
</form>
</body>
</html>





Return Statement

Another thing that a function can do is return a value.The return statement
returns a value back to the function.
Example:

<html>
<head>
<script type="text/javascript">
function Division(x,y)
return x/y;
</script>
</head>
<body>
<input type="button" value="returns Value" onclick="Division(12,6)"/>
</body>
</html>







Note:After the return statement the function stops and it does'nt execute the lines below it.