JavaScript function declaration, function expression, Function constructor, Anonymous function

December 25, 2012

Function declaration –

function name([param[, param[, ... param]]]) {
   statements
}
example -
function sum(a, b)
{
    return a + b;
}

name – The function name

param – The name of the argument to be passed to the function. A function can have up to 255 arguments.

statements – The body of the function

Function expression and Anonymous function –

function [name]([param] [, param] [..., param]) {
   statements
}
example -
var sum = function(a, b) { return a + b; }

The name can be omitted in which case it becomes anonymous function.
Anonymous functions can help make code more concise when declaring a function that will only be used in one place.

Function constructor –

Function objects can be created with new operator

new Function (arg1, arg2, ... argN, functionBody)

example - 
var sum = new Function('a','b', 'return a + b;');

arg1, arg2, … argN – zero or more names to be used by the function as argument names

functionBody – A string containing JavaScript statements forming the function body.

References
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope

http://helephant.com/2008/08/23/javascript-anonymous-functions/

http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work

 


javascript void(0) for HTML link

May 27, 2012

To create a HTML link which does nothing when user clicks it,  use  like below


<A HREF="javascript:void(0)">Click here to do nothing</A>

When the user clicks the link, void(0) evaluates to undefined, which has no effect in JavaScript.

References –

https://developer.mozilla.org/en/JavaScript/Guide/Expressions_and_Operators#void

Here is a stackoverflow.com link, which answers why  void(0)  is better than using #  for this requirement

http://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0