Welcome to the GEEK world, best place where you find topic about latest cutting edge technology on website and mobile. Learn and grow your knowledge with the information and tutorials about Website designing, CSS tutorials, Java Script tutorials, Ruby tutorials, ROR tutorials, HTML tutorials, HTML5 , JQuery, Javascript tutorials, Photoshop tutorials, Flash, games tutorials, Cheat sheets, Design tools, Action Scripts as well as MySql, Oracle and many more in a easy way to use and understand.

Friday, September 5, 2014

Javascript: Introduction to Anonymous functions

Anonymous functions are functions that are dynamically declared at runtime that don’t have to be given a name.

Anonymous functions are declared using the function operator. You can use the function operator to create a new function wherever it’s valid to put an expression. For example you could declare a new function as a parameter to a function call or to assign a property of another object.

Logically they are the same. However, the second one is an expression, an anonymous function assigned to a variable 'dosomething'; The first one is a function declaration, but the second one is a function expression.
It's got the parenthesis around it (and trailing) so that the function is called immediately.

The most common use for anonymous functions are as arguments to other functions, or as a closure.

setTimeout(function() {
dosomething();
}, 1000);

// Our anonymous function is passed to setTimeout, which will execute
// the function in 1000 milliseconds.

Anonymous functions are used for the reasons of:
a) code brevity: It often makes sense to use anonymous functions calls in callbacks and event handlers;
b) scope management: Anonymous functions can be used to create temporary/private scope;
c) Anonymous function are often handy in closures and recursions.

Recursions : Recursions
are functions that call themselves, they are often used to solve
problems such as factorials, the tower of hanoi, golden ratio (See wiki Recursion. Or, fibonacci numbers.
function fibonacci(n) {
if (n < 2)
return n;

return fibonacci(n - 1) + fibonacci(n - 2);
}

alert(fibonacci(6)); //8

It works fine. But it can/should be improved with two things: arguments.callee and function memorization. As the following: