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?

4
  • 1
    Exact dupliate: stackoverflow.com/questions/336859/… Commented Sep 2, 2012 at 14:09
  • Aka. "named function vs anonymous function" in technical terms. Commented Sep 2, 2012 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' Commented Sep 2, 2012 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. Commented Oct 17, 2012 at 3:25

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.