0

What's the difference following two cases?

Using use strict at the top of the file, not in a function

"use strict";

(function () {
  // ...
})();

Using use strict in the wrapping function

(function () {
  "use strict";
  // ...
})();

I read in a blog post that putting use strict at the top of the file (not in a function) could have unforeseen effects.

Also, from what I remember jshint recommends putting it into a function too.

So, why is it better to have it into a function instead of putting it in the top of the file?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • Another dupe – [__Why is 'use strict' usually after an IIFE (rather than at the top of a script)?__](http://stackoverflow.com/questions/38670872/why-is-use-strict-usually-after-an-iife-rather-than-at-the-top-of-a-script/38670885#38670885) – Rayon Aug 09 '16 at 10:48
  • @Rayon Thanks! But still, I don't get it: why would I enable the strict mode only inside of a function? Isn't it better to use it globally, in the entire file? – Ionică Bizău Aug 09 '16 at 10:53
  • From _docs_, _If you are using strict mode for entire script, it isn't possible to blindly concatenate non-conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Concatenation of strict mode scripts with each other is fine, and concatenation of non-strict mode scripts is fine._ – Rayon Aug 09 '16 at 10:54
  • @Rayon But supposing I have code written only in strict mode, doest that apply? – Ionică Bizău Aug 09 '16 at 11:06
  • No, bu on many occasions, we use external libraries which may not work under `"strict mode";` – Rayon Aug 09 '16 at 11:07
  • @Rayon So, `"use strict"` is applied globally across all the loaded files, not only the current file? – Ionică Bizău Aug 09 '16 at 11:45
  • It happens when we concatenate JS files over production... – Rayon Aug 09 '16 at 11:47
  • @Rayon Ah, got it! Makes sense. – Ionică Bizău Aug 09 '16 at 13:44

0 Answers0