-1

What does (function($) {})(); mean?

user2864740
  • 54,112
  • 10
  • 112
  • 187
Shahin
  • 83
  • 2
  • 13
  • Its an in-line function – craig1231 Aug 13 '14 at 09:10
  • The use of the `$` parameter looks bogus - like perhaps it was really supposed to be `jQuery(function ($) {..})` or `(function ($) {..})(jQuery)`. Make sure to write questions accurately. – user2864740 Aug 13 '14 at 09:13
  • `(function($) {})();` is a self executing anonymous function, same as here `(function(){} )();` The difference is in first one you passed $ (jquery) as an argument to function. This function will be called as soon as it's parsed. This has been already discussed here: http://stackoverflow.com/questions/19491650/self-executing-function-jquery-vs-javascript-difference – SSA Aug 13 '14 at 09:15

2 Answers2

1

Its an Immediately-Invoked Function Expression (IIFE).

It means that the code between the curly braces will be executed as soon as its parsed and inside a closure. This means that any variables declared inside the function body with var will be discarded from memory after the function is finished executing. This is a way to isolate code and prevent namespace polution. You can also use this to rename variables for a particular scope:

For example, consider jquery:

(function($){
  //inside the closure, jquery can be accessed using '$'
  $(...)
})(jquery);

or

(function(customJqueryName){
  //inside the closure, jquery can be accessed using 'customJqueryName'
  customJqueryName(...)
})(jquery);

Check out closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
IIFE: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

orourkedd
  • 5,771
  • 4
  • 39
  • 63
0

It's an anonymous inline-function, which will be called just after definition.

GolezTrol
  • 109,399
  • 12
  • 170
  • 196
Mritunjay
  • 22,738
  • 6
  • 47
  • 66
  • 1
    Essentially true, although one might like a use case, or at least the name for this pattern (IIFE), so one can put this answer in context. – GolezTrol Aug 13 '14 at 09:31