Functions

Like many other programming languages, functions make the core part of javascript. A function is basically a bunch of statements which are executed simultaneously whenever the function containing them is called. We can call functions in javascript to handle any event.

To keep the browser from executing a script when the page loads, you can put your script into a function.

A function contains code that will be executed by an event or by a call to the function. You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file).

Functions can be defined both in the head and in the body section of a document. However, to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the head section.

Defining a function
function myFirstFunction(){
   alert('This is my first function.');
   anotherFunction(); // calling to another fn
   // do something more
   }

The above example shows both an example to define a function and call a function. Many a times a function is called by the event handler as disussed earlier

The function can also return some value if it is used to calculate some value. Here is an example showing the same :-

function giveSum(a,b) {
   return (a+b);
}

sum = giveSum(1,2); // calling the fn

Here the function returns the sum of the two numbers passed to the function giveSum()

Lets proceed to see some loops used in Javascript.

Member Login

Member Login




Not a Member? Sign Up!




Login to comment

Be the first to comment on this topic







  


<<< Wanna review

Continue >>>