How does the (function() {})() construct work and why do people use it?

With the increasing popularity of JavaScript frameworks, the $ sign was used in many different occasions. So, to alleviate possible clashes, you can use those constructs:

(function ($){
  // Your code using $ here.
})(jQuery);

Specifically, that’s an anonymous function declaration which gets executed immediately passing the main jQuery object as parameter. Inside that function, you can use $ to refer to that object, without worrying about other frameworks being in scope as well.

Leave a Comment