Search code examples
javascriptcompiler-warningsstrictstrict-mode

Is it a good practice to wrap "strict mode" inside an IIFE (self-invoked) expression?


I have one very simply question to ask:
Is it a good practice to wrap code inside an IIFE whenever I intend on using "use strict" ?


Now, I do understand the usefulness of Scope Closure (answered here and here) or probably better yet, the usefulness of the ever-so-prevelant module approach to design and why IIFE is such a powerful tool to be used (not only) in these scenarios, but that's not what this question is about.

What I've noticed, most linters (jsfiddle included) do tend to complain whenever you want to use strict mode in the global scope:

enter image description here

Wrapping the block inside IIFE seems to stop the linter from complaining

(function(){
	"use strict";
	console.log("I compiled!");
})();

Is there any basis as to why should use strict; be kept inside IIFE, or is this just a "baseless objection" raised with no proper reason behind it?


Solution

  • If multiple scripts are bundled together into a single file, a single "use strict"; at the top makes all script code in that one file strict, which may cause problems for some of the bundled scripts if they're not designed to work in strict mode. (This isn't a problem if they're included by different script tags, only if they're bundled.)

    Is it a good practice to wrap code inside an IIFE whenever I intend on using "use strict" ?

    If you're using a bundler, probably. If not, it doesn't really matter. Increasingly, though, as ES2015's modules become more well-supported, using modules (which you can do with bundlers today) would be an even better choice, and there's no need for the "use strict" directive at all (ES2015+ module code is always strict).