Sunday, September 26, 2010

Javascript Functions for Dummies

A common confusion is when to use "function", "new function" and "new Function"

1. Plain "function" is simply code that does a particular task. It can be called directly or by an event (similar to module/procedure/subroutine in other languages). It typically returns a value.
function AreaOfCircle(r){
return Math.PI*r*r;
}
//Now call the function as:
alert(AreaOfCircle(3));

You can declare an anonymous functions as:
function(){
...
}

You can declare the function and execute it immediately. For example:
alert(
function(){
alert("executing function...");return "done!";
}() //execute function, and alert the returned value
);

Note:
function Foo(){ ... }
is shortcut for:
var Foo = function(){ ... }
//Creates an object with code which can be called as Foo();


Check this out:

var x=function f(){};
console.log(x?true:false)
console.log(x()?true:false)

The first one will return true, as "function" is like an object and returns "truthy". the second one OTOH executes this empty function and returns "undefined", which essentially is "falsy".

2. The "new" keyword basically returns an object based on the code specified inside the function.
var o = new function(){...} is shortcut for:
function Foo()
{
this.x = 1;
this.y = 2;
}
var o = new Foo;

This creates an object "o" with two properties: x and y. Basically this does the exact same thing as the two examples below:
//Object instantiation
var o = new Object();o.x=1;o.y=2;
//A more compact Object Literal Notation:
var o= {x:1,y:2};


3. Finally, there "Function constructor" which allows you to create a function by passing strings for function-parameters and function-code:
var a=new Function("x","y","alert(x+y)"); //last string is the code
a(3,4); //results in "7"

Note the capital "F" in the function constructor. Also note this constructor does not create a closure.

Object-oriented javascript tutorials can be found at: mckoss, javascriptkit, and sitepoint

More javascript essential study material: Douglas Crockford YUI videos on JS reintroduction. And if you are feeling confident, go take the javascript quiz on kourge.net - you'll be humbled pretty quickly!