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?