Tuesday, June 12, 2012

JavaScript Functions - Part 1


A function is a block of code which will execute whenever it is called. To become a good JavaScript programmer understanding functions are the key.

In JavaScript functions are declared with function keyword. It is possible to create named functions, anonymous functions / lambda functions, self invoking functions. You can pass parameters to functions; these parameters can be any JavaScript type.

// named function
function myfun(){
document.write(“this is simple named function”);
}
// named function with params
function myfun (name,age){
document.write(“My name is “  +  name,  “ I am “  +  age);
} 

To call a function we have to use () operator. In the above example myfun is the function name so you can call function like below.

//invoking a named function
myfun(); 

All the declared parameters are local variables to the functions. You can omit declared parameters; misplace the order of parameters, mismatch data types when calling a function, it is perfectly legal in JavaScript.

//ignored age param
myfun("srinivas"); // prints srinivas
//params are local varibles to the function
function myfun(name,age){
name = "srinivas";
age = 23;
document.write(name," " + age);
}
myfun("something", 25); // prints srinivas 23
Functions are objects in the JavaScript. so you can pass them as parameters and can assign to the variable.

// creating a anonymous function and assigning them to a variable
var printNameAge = function(name,age){
document.write(name," " + age);
}
// whenever you need to call this anonymous function need to call like below
printNameAge('srinivas',23); // prints srinivas 23

Variables / parameters declared in the functions are private variables. If you want to make them as public use ‘this’ keyword.

//using the this key word
function myfun(name,age){
this.name = "srinivas";
this.age = 23;
document.write(name," " + age);
} 
myfun("something", 25); // prints something 25

Self invoking function is a function which will invoke itself. by using these we can create some utility functions and modules. These are very helpful to make the global space clean and avoid name space collisions.

// simple self invoking function
(function(){alert('hi')})();

Summary
  1. Functions are declared with the function key word, every function has a body with some statements.
  2. Functions will be executed with the () operators.
  3. Functions may or may not have parameters
  4. It is perfectly legal omitting some of the parameters, passing them in a different order, passing different types.
  5. Functions can be named functions, anonymous functions, self invoked functions
  6. Function parameters are local variables to the functions
  7.  By default declared variables in the function are private, to make them as public use ‘this’ keyword.