I want to know the difference between following javascript functions. Can someone help whats the difference and in what circumstances do we need to use these two functions?
define(function () {
});
the second one is self executing function which is below
(function() { })();
Update
I am using requireJS
Your question title mentions a “jQuery function” but there is no jQuery in the code you’ve shown.
The first bit of code:
…calls a function named
defineand passes an anonymous function as a parameter (some kind of callback?)The second:
Defines an anonymous function and calls it immediately.
Consult the RequireJS API documentation for guidance on when to use the
define()function. As for an immediately-invoked-anonymous-function as in your second example there are many different reasons why you might use such a structure, e.g., a common reason is to create working variables and/or nested functions without creating globals.To my way of thinking comparing the two (without more context, anyway) doesn’t make any more sense than comparing
setTimeout(function(){ },1)with(function() { })();(or comparing any other random function that takes a function as a parameter).