Should I 'use strict' for every single javascript function I write?
What is a good practice to use strict in a large AngularJS project? Using it globally can break a third party library that doesn't support it, but doing 'use strict' every single time is just a lot of repetition.
On this question, do beware a general tendency to oversimplify.
First, all of your code absolutely should be run in strict mode. Core modern javascript functionality is changed (see .call() and apply()) or disfigured (silent Errors) by executing code outside of strict mode. (More on this here, from Crockford.)
However, that doesn't address how you should ensure that your code runs in strict mode. There are at least two contexts to consider:
In the browser, your code should be delivered after being minified. 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. One approach is to wrap your minified code in a single IIFE closure as part of the build process:
;(function (){
'use strict'
// All code here.
}())
This, I think, is close to the ideal way of doing it, but it more or less dictates that you adopt a continuous integration workflow (since, to observe your code running in strict mode, you must have it all wrapped up one closure). If you don't work that way, you'll have to include the use strict
directive at the top of every function that isn't being declared within another function's scope.
On the server, it's much simpler, of course. Code isn't minified, and bytes don't matter, so you can just include the use strict
directive at the top of every file.
A word of warning on --use_strict
: In cases where you control how scripts are run, you may find yourself tempted to use the --use_strict
runtime flag. It's easy, but it means all dependencies must be strict mode compliant. Since you can't control every third-party's compliance, this is usually unwise.