Monday, September 3, 2012

Javascript functions

(A) The standard way - the Function Definition

This is the std. way a function could be written in Javascript. It's easily recognisable from major programming languages: it has the function keyword, a name, parameters, a function body delimited by curly-braces, and a return.
It is also useful to know, or it might just be interesting, that functions are Objects.

function square(x) {
    return x * x;

Invoked by:

(B) Standard function declaration assigned to a variable - the Function Expression

This next example assigns the function to a variable. The interesting here is that you can not invoke the function by the function name. You must invoke it by the variable name.

var squareFunction = function square(x) {
    return x * x;

Invoked by:

Anonymous function

This next one is the Anonymous function. It is a simplification of the previous.
The function name is omitted. It is usual to use this anonymous version as it is less verbose, however the previous one can be useful when debugging as the function name will appear in the call stack.

var squareFunction = function (x) {
    return x * x;

Why the two ways and which one should I use

There are two benefits to using the Function Expression (assigning the function to a var)
1. One is it keeps the function name to the local scope and doesn't pollute the global namespace.
2. The name will show up in debuggers.

The immediately invoked anonymous function

The difference is
1. Wrap the function in brackets
2. Immediately invoke the function afterwards

( function (x) {
    return x * x;

This is used a lot in jQuery.


Go and read Dmitry's blog on functions for the whole story. Now here's a bloke who knows his stuff.

No comments:

Post a Comment