14

I'm refactoring an old AngularJS 1.3 project. One of the things I noticed is that the person who made this started every single file of AngularJS code with:

(function () {
'use strict';

  angular.module('app').factory('Employees', ['$http', function($http) {
    // angular code removed
  }]);

})();

Does using function() 'use strict' in every single file any benefit to the code? To me it feels like a waste of 3 lines in every single file. Is there a standard / best practice for this?

Sophie
  • 193
  • 1
  • 7
  • I know what 'use strict' does. But I would like to find a way to only use 'use strict' once without making it global. – Sophie Feb 09 '17 at 17:55
  • See also [Why is 'use strict' usually after an IIFE (rather than at the top of a script)?](http://stackoverflow.com/questions/38670872/why-is-use-strict-usually-after-an-iife-rather-than-at-the-top-of-a-script) – Bergi Feb 09 '17 at 17:56
  • "*only use 'use strict' once without making it global.*" is exactly what your code does, it makes the *module* strict. – Bergi Feb 09 '17 at 17:57

2 Answers2

4

Using use strict helps you to prevent problems with closures and variable scopes.

For example, if you accidentaly set a global variable - in this case by forgetting to add var keyword in the for loop, use strict mode will catch it and sanitize.

(function(){
  for (i = 0; i < 5; i++){
  }
  console.log(i);
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }

(function(){
  'use strict';
  for (i = 0; i < 5; i++){
  }
  console.log(i);
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }
kind user
  • 40,029
  • 7
  • 67
  • 77
3

If you put 'use strict'; outside the IIFE you make it global.

That means it is possible that code you have no control over (other libraries for example) that isn't strict compliant might cause problems.

Just like variable scope, you are only scoping 'use strict' within the context of your code only by putting it all inside the IIFE

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • I would however assume that libraries which choke on being run in strict mode have other problems… – Bergi Feb 09 '17 at 17:58