Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'use strict' usually after an IIFE (rather than at the top of a script)?

Tags:

javascript

I've anecdotally noticed that use strict appears to be more common like this:

(function() {
  'use strict';
  ...

Than this:

'use strict';
(function() {
  ...

The vanilla JS implementation of TodoMVC does this, for example.

Is there a reason for this?

Edit: I'm aware of the whole-file versus function-block distinction. TodoMVC is a good example to demonstrate why this placement is strange to me, because it doesn't rely on any external libraries, so the whole "play nice with non-strict third parties" doesn't apply here.

like image 313
Kayce Basques Avatar asked Dec 03 '22 14:12

Kayce Basques


1 Answers

Declaring it in local scope will enforce function block to be considered under strict-mode by browser.

You can have non-strict observation for other code outside of the IIFE


Inside IIFE:

(function() {
  "use strict";
  a = 100;
})();
b = 200;

For entire script:

"use strict";
(function() {
  try {
    a = 100;
  } catch (e) {
    console.log(e + '');
  }

})();
b = 200;

As highlighted in 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. Only concatenating strict and non-strict scripts is problematic. It is thus recommended that you enable strict mode on a function-by-function basis (at least during the transition period).

You can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. This eliminates the concatenation problem but it means that you have to explicitly export any global variables out of the function scope.

like image 98
Rayon Avatar answered May 23 '23 02:05

Rayon