Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of using "function() 'use strict'" in every file? [duplicate]

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?

like image 967
Stefan1991 Avatar asked Feb 09 '17 17:02

Stefan1991


People also ask

Why do we use use strict?

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 −

How does strict mode work in a script?

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.

Should I include 'use strict' in all my function definitions?

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.

What is the use of strict context in JavaScript?

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.


1 Answers

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; }
like image 156
kind user Avatar answered Sep 20 '22 17:09

kind user