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

	"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?



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).


I think that is because when use strict is defined globally you will end up forcing all your 3rd party reference to not work properly unless they are strict as well. Now because you do not have the power to guarantee that all loaded resources will be using strict, you are in danger of causing troubles...

Using "strict" inside a scope mean that the owner of the scope is responsible to know if his code is supporting strict or not


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.