Wednesday, December 19, 2012

Back to basics - Function Declarations

In this simple post I am going to show you what's the preferred way of declaring JavaScript functions. We are going to create anonymous functions and assigning them to a variable.

This is an anti pattern in JavaScript (don't do this):
The preferred way of declaring a JavaScript function is creating anonymous function and assigning it to a variable:
Benefits of this type of function declaration are:

1. Makes it easier to understand "functions as an object".
2. It enforces good semicolon habits.
3. Doesn't have much of the baggage traditionally associated with functions and scope.

Also we can declare named function expression as follows:
Benefits of this type of function declaration are:

1. Provides the debugger with an explicit function name: helps stack inspection.
2. Allows recursive functions: someFunction can call itself.

But with this type of function declaration there are historic quirks with IE.

3 comments:

  1. so why don't do this? when you use it like a class? I mean for something like var someInstance = new someFunction(); makes more sense, doesn't it?

    ReplyDelete
  2. var myClass= function someFunction() {
    };

    the upper code defines a class. So, you will use 'new' keyword when you instantiate that class.
    Like bellow---
    var myObj1=new myClass();
    var myObj2=new myClass();

    if you use your 'new' keyword in this way, you will gain the power of re-usability;

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete