garrettmac
garrettmac

Reputation: 8585

Are there any benefits to wrapping angular javascript file with the "(function() { ....[js code here]...... })();"

Simple questions I've always wondered.

I started with angular without a vanilla javascript background I'm pretty sure that's that this is, but sometimes I see javascript files that have the:

(function() {
   'use strict';
   ....
})();

at the start and finish of a file like:

(function() {
   'use strict';

   angular.module('asdf', []);
   angular.controller('asdf' function(){.....})
})();

I don't use it and and everything runs fine. So my question are there any benefits by wrapping my javascript files inside of them?

Upvotes: 0

Views: 136

Answers (2)

Paul
Paul

Reputation: 141827

The anonymous IIFE surrounding it causes variables to be in a new scope, instead of the default scope, which in a browser is global. See: What is the (function() { } )() construct in JavaScript? for more info.

The 'use strict'; activates strict mode inside the IIFE, which means that some edge cases in JavaScript will behave differently (EG. throwing an error instead of strange behaviour). For more info about strict mode, take a look at the MDN article.

Upvotes: 0

Dominik
Dominik

Reputation: 2906

So, what you're looking at there is an imediately invoked anonymous function.

Basically, this "pattern" is used, because if you're not using it, you're working in the global namespace javascript out-of-the-box runs in, which could lead to unwanted problems including third party libraries/plugins or other modules you wrote. More insight here, there or here

Upvotes: 4

Related Questions