JavaScript Functions

A function is a collection of statements that is executed when it is called at some point in a program.

JavaScript functions are nothing, but a block of code designed to be perform a specific task.

Define Function in JavaScript

To define a function in JavaScript, use function keyword, followed by the function name, which is followed by the parentheses (contains parameter list). Here is the general form shows how to define a function in JavaScript:

function funName(parameter1, parameter2, parameter3) {
    code to be executed here

Note - The arguments inside functions are used as local variables.

Here is an example of defining a function in JavaScript:

<script type="text/javascript">
function funName(parameter-list)
  statements list

Let's look at the following example of JavaScript functions, which takes no parameters called fun1 is defined below :

<script type="text/javascript">
function fun1()
   alert("Hello JavaScript, I am Statements of Function Definition");

Call a Function in JavaScript

To call a function in JavaScript, you have to simply write the name of the function which is going to be called. Here is an example:

<script type="text/javascript">

After calling the above function fun1() which is define in the second above code fragment, the function will tells the browser to give an alert box containing the string "Hello JavaScript, I am Statements of Function Definition"

You will learn all about functions in JavaScript divided into the following tutorials:

JavaScript Function Example

Here is an example demonstrates function in JavaScript. Here we are using a simple JavaScript function that displays an alert box on the load event of the Web page.

   <TITLE>JavaScript Function Example</TITLE>
   <SCRIPT language="JavaScript">
   function javascript_function()
      alert("This is an alert box from javascript_function() function.")
<BODY onload="javascript_function()">


Here is the output produced by the above JavaScript Function example.

javascript function

JavaScript Online Test

« Previous Tutorial Next Tutorial »