3

There are two common ways to declare a javascript function

Way 1: Named Function

function add(a, b) 
{                     
  return a+b;
}

To call the above function we use add(3,4);

Way 2: Anonymous function

var add = function(a, b) 
{                     
    return a + b;
} 

To call this function we again use add(3,4);

Both produce the same result. I always go with way 1 as I learned javascript this way. But most of the new javascript libraries like jQuery seem to use way 2.

Why is way 2 preferred over way 1 in most of the javascript libraries? As per my understanding both produce the same behaviour. The only difference is in way 1, the function is available to code that runs above, where the function is declared, which is not true in Way 2. Is this the only reason new javascript libraries uses the the way 2, so that they can ensure their libraries are included first and then call their function?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
M Sach
  • 33,416
  • 76
  • 221
  • 314
  • 1
    Exact dupliate: http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname – jacktheripper Sep 02 '12 at 14:09
  • Aka. "named function vs anonymous function" in technical terms. – inhan Sep 02 '12 at 14:14
  • Guys probably i was not clear in asking my question. My main motive was why some javascript libraries like jquery prefer anonymous function over named functions. For example we use $("#custId") where $ is variable assigned to function 'jquery' – M Sach Sep 02 '12 at 14:17
  • While I myself also prefer the "named function" way, I think one of the reasons most JS library recommends "anonymous function" or _closure_ is to avoid potential name conflict. – Passerby Oct 17 '12 at 03:25

1 Answers1

1

Anonymous functions are used to comfortably define objects. The reason libraries often drop the named declaration and only use anonymous (even when its not specifically needed) is to improve code readability, so you dont have two ways to declare one thing in your code.

var x = function() {
   //constructor
}

x.y = function() {
   //first method
}
roacher
  • 666
  • 3
  • 8