Posted By:
26 Aug, 2014 10:57 am PDT

Functions in JavaScript

How to we use functions in JavaScript? Are functions there in JavaScript?

Please tell me with the help of a simple example.

Attachment:None


JavaScript Functions

A function is a group of reusable code which can be called anywhere in your programme. This eliminates the need of writing same code again and again. This will help programmers to write modular code. You can divide your big programme in a number of small and manageable functions.

Like any other advance programming language, JavaScript also supports all the features necessary to write modular code using functions.

Before we use a function we need to define that function. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here:

<script type="text/javascript">

<!--

function functionname(parameter-list)

{

  statements

}

//-->

</script>

 

Example:

A simple function that takes no parameters called sayHello is defined here:

<script type="text/javascript">

<!--

function sayHello()

{

   alert("Hello there");

}

//-->

</script>

 

Calling a function

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

<script type="text/javascript">

<!--

sayHello();

//-->

</script>

 
Was it useful?  




Please login to reply to this problem.