In-depth guide to javascript functions

Anonymous functions
Sometimes you need a simple function without the need of assigning it to a name. This is called a anonymous function and I will give some examples of the usage.
- var nums = [1, 4, 3, 2, 6, 2, 0];
- nums.sort( function(a,b){ return a-b; } );
To sort a list of integers the sort-method expects a function as a parameter. This function can be defined directly within the parameter section of the sort-method by using the function literal.
- var calculator = {
- 'add': function(a, b) { return a + b}, 'sub': function(a, b) { return a - b},
- 'mul': function(a, b) { return a * b}, 'div': function(a, b) { return a / b}
- };
- calculator.sub(3, 3); // 0
- calculator.add(3, 3); // 6
- calculator.mul(3, 3); // 9
In this example I created directly an object with some function properties. It looks like a simple calculator, the feature is to assign functions directly to object properties.
- (function (){
- var max = 20;
- function square(a) { return a*a; };
- for (var i=0; i<max; i++) {
- document.write("The square of "+i+" is "+square(i)+"<br/>");
- }
- })();
If you offer scriptlets to include a function directly in other peoples html-code it would be great to define no new variables in the global namespace. A common solution is to put your code in a anonymous function, work with local variables and execute this function directly. Remember: the return value of a function definition is the function himself, and the parentheses after a function will execute it: syntax is (function(){;})() .
- function sequence() {
- return arguments.callee.internal++;
- }
- sequence.internal = 0;
- sequence(); // -> 0
- sequence(); // -> 1
- sequence(); // -> 2
- sequence(); // -> 3
How to build a simple singleton - a function who produce a sequence. We don't need to define a new prototype or a global variable. First we define a function. Because its a Object we can set a property named internal and assign it with 0. When calling the function with the callee-reference we can access to the property internal (Yes, its not internal - it is public accessible for everyone).
eval is evil
- eval("function square(n){return n*n;}")
eval is a global function! It evaluate the JavaScript given as the first parameter string and return the last statement (if more included). Don't use the second parameter (JS 1.5 Definition) or try to use the eval property of window or this (Rakesh Blogpost)!
Now eval works like expected:
- var test = function(){return eval("var i1 = 5; i2 = 7;");};
- var i1 = 1;
- var i2 = 2;
- var i3 = test();
- var i4 = eval(test());
First the function test will filled with to assignments in the function body and returning the result of eval. After executing i1 is not changed, because in test there is a new local i1 defined. After this the global variable i2 is overwritten with 7. And the result of test() is 7. The end test returns only the result of test because if eval don't get a string as argument it does nothing and returning the argument[0] !
Use eval only if you really need it. For example don't use it for accessing object properties like this:
- ob = {"a1": "yeah", "a2": "other", "a3": "more");
- //Accessing via eval
- for (i=1;i<4;i++) { document.write(i + " = " + eval("ob.a"+i)); }
- //Accessing via [name]
- for (i=1;i<4; i++) { document.write(i + ": " + ob["a"+i]); }
conclusion
After reading this very detailed article about the different possibilities in which a JavaScript function can be defined, hopefully you won't ever again stumble upon a specimen without recognizing it as such.
Trackback URL for this post:
http://united-coders.com/trackback/21
in-depth guide to javascript functions
from DotNetKicks.com on Thu, 05/07/2009 - 13:48You've been kicked (a good thing) - Trackback from DotNetKicks.com

Comments
Anonymous - Wed, 06/03/2009 - 10:44
Please display complex function for those who wants to expertise in javascript..............
Christian Harms - Fri, 06/05/2009 - 20:15
What are "more complex function"? You want a class design or more mathematical functions? I will plan in both directions.
Combining HTTP and JavaScript APIs with php | united-coders. (not verified) - Sat, 04/03/2010 - 11:46
[...] The function wrapper chooses all positions with a set city, hoping these lat/long value pairs are the most accurate [...]
Tutorial for a IP to geolocation aggregator script | united- (not verified) - Fri, 04/23/2010 - 20:46
[...] javascript interface is ugly and the data defing global functions, which can't be removed from the global [...]