Different ways to declare a Javascript Function

December 24th, 2008 Posted in Web 2.0

There are different ways to declare a Javascript function. Even though all of them are doing the same and valid there are differences on how they are handled in the background.

In the usual way of declaring a function the content of the function is compiled but not executed until we call the function and also an object with the same name as the function is created

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

We can also declare a function by assigning a variable to an unnamed function. Using this syntax we will feel the function as a object more than the usual method

var addNumbers = function (a, b) {
      return a+b;
}

We can use the above syntax with the named function and we can refer to the function by the name or by the variable.

var addNumbers = function addNum(a, b) {
      return a+b;
}
alert(addNumbers(3,2));
alert(addNum(3,2));

We can also declare a function using the “new” operator.This syntax tells JavaScript that we want to create an object of type Function. Note also that the parameter names and the function body are passed as Strings. We can have as many parameters as we want, JavaScript knows that the function body is the String right before the closing bracket

var addNumbers=new Function(”a”, “b”, “return a+b;”);

Declaring function in this way causes the function not to be compiled, and is potentially slower than the other ways of declaring functions. Note that “new Function()” uses capital F, not lower case f

One Response to “ Different ways to declare a Javascript Function ”

  1. sushma says:

    can u send me some example of javascript function realting to how can we delete a control

Leave a Reply