Wrapping controller in anonymous function

angularjs

Solution

Both will work. The reason you'll find a lot of JavaScript code wrapped in an anonymous function is to isolate it from other code on the page.

The following code will declare a variable called `name` on a global scope:

var name = "Hello World";

By using that code, any other script on the page attempting to use a variable called `name` could potentially get an unexpected value of `"Hello World"` because your script declared it as `"Hello World"`.

By wrapping that code in an anonymous function, you keep the code from conflicting with other variables called `name`:

(function() {
    var name = "Hello World";
})();

In the example above, `name` is now only available inside of the scope of the anonymous function. It is not global, and therefore cannot conflict with other code on the page.

In the second code snippet you provided, `app` would now be a global variable that could potentially be overwritten by someone else declaring a global variable called `app`. By wrapping your Angular module in an anonymous function, you prevent your code from conflicting with other code.

Additionally, other people who may use your code won't have to worry about it changing their global scope.

Problem

whether i do: ``` (function () { 'use strict'; // Create the module and define its dependencies. var app = angular.module('app', [ // Angular modules 'ngAnimate', // animations 'ngRoute' // routing // Custom modules // 3rd Party Modules ]); // Execute bootstrapping code and any dependencies. app.run(['$log', function ($log) { $log.log('we are loaded'); }]); })(); ``` or ``` 'use strict'; // Create the module and define its dependencies. var app = angular.module('app', [ // Angular modules 'ngAnimate', // animations 'ngRoute' // routing // Custom modules // 3rd Party Modules ]); // Execute bootstrapping code and any dependencies. app.run(['$log', function ($log) { $log.log('we are loaded'); }]); ``` Both seem to work -- what is the difference? I would appreciate explanation on what an anonymous function is, when i would use one, and why I see controllers written both ways for AngularJs. Thanks!

Original source