0

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?

angelcool.net
  • 2,505
  • 1
  • 24
  • 26
garrettmac
  • 8,417
  • 3
  • 41
  • 60
  • 1
    read http://benalman.com/news/2010/11/immediately-invoked-function-expression/ and http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript – Mauricio Poppe May 04 '16 at 03:49
  • There are no benefits provided by an IIFE given the specific code in your question. – Ray Nicholus May 04 '16 at 03:50
  • wow that was the quickest question I've ever gotten answers too, thanks guys. These answer my question but I found It's already been asked and marked it as a duplicate – garrettmac May 04 '16 at 04:03

2 Answers2

4

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

Community
  • 1
  • 1
Dominik
  • 2,801
  • 2
  • 33
  • 45
0

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.

Community
  • 1
  • 1
Paul
  • 139,544
  • 27
  • 275
  • 264
  • Not sure why this answer was downvoted. This answers the question better than the accepted answer, and is more technically correct. – Ray Nicholus May 04 '16 at 15:29