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?
In JavaScript Why do we use "use strict"? Strict Mode is a feature introduced in ES5 that allows you to place a program, or a function, in a “strict” mode. This strict context prevents certain actions from being taken and throws more exceptions (generally providing the user with more information). Some specific features of strict mode −
If you add it to the 'top' of a script the mode is triggered for the entire script is executed in strict mode. If placed within a function strict mode is limited to the function's scope.
If you include 'use strict'in every function body, your minifier won't strip it out, and you'll waste bytes repeating it everywhere. You only need it in your outermost function scope(s)—at the top of your module definitions.
This strict context prevents certain actions from being taken and throws more exceptions. The statement “use strict”; instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript. Benefits of using ‘use strict’: Strict mode makes several changes to normal JavaScript semantics.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With