0

I've seen a few developers tout 'best practices' when wrapping angular components in anonymous functions. For example:

(function(){
     angular.controller('MyCtrl', [function(){
         // ... controller logic
     }]);
})()

What is the benefit of wrapping angularjs components in anonymous functions, if at all any?

Carlos Pliego
  • 859
  • 1
  • 8
  • 19

1 Answers1

0

This is an immediately invoked function.

(function(){

})()

The above will declare an anonymous function that will be called immediately.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • 1
    In theory every function is a closure in JS... – Felix Kling Aug 04 '15 at 22:41
  • Could you please explain this more? Thank you very much in advance :) – Christos Aug 04 '15 at 22:42
  • A closure is a function that has a reference to the environment it was created in to resolve free variables. That's what all functions in JS do (in theory, browser may optimize). Besides, whether the function is a closure or not is irrelevant. Pointing to IIFE is correct though. – Felix Kling Aug 04 '15 at 22:44
  • Ok, I got it and I re-edited my answer. Thank you ! – Christos Aug 04 '15 at 22:45