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?

3
  • I know what 'use strict' does. But I would like to find a way to only use 'use strict' once without making it global. Commented Feb 9, 2017 at 17:55
  • See also Why is 'use strict' usually after an IIFE (rather than at the top of a script)? Commented Feb 9, 2017 at 17:56
  • "only use 'use strict' once without making it global." is exactly what your code does, it makes the module strict. Commented Feb 9, 2017 at 17:57

2 Answers 2

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; }

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I would however assume that libraries which choke on being run in strict mode have other problems…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.