I was learning JS and came across 'use strict'. Then, here Should I 'use strict' for every single javascript function I write? @Bergi says that "you only should put 'use strict' in the module scope - once per file - so that it is inherited by all your functions". Is it true that by "it is inherited by all your functions" means each function in a certain module uses 'use strict' inside of itself?
-
http://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-code – George Mar 05 '20 at 10:12
-
any `type="module"` script is automatically in strict-mode, yes. – ASDFGerte Mar 05 '20 at 10:13
-
@ASDFGerte, so e.g if we have function like function Addition(){'use strict'}, each function inside es module has use strict in itself. Right? – Wertu Mar 05 '20 at 10:22
-
If you are using native JavaScript modules, then *all* the code within your modules will be in strict mode by default. If you are using older hand-rolled modularisation patterns, then you will need to declare `'use strict'` at the top of the module. – Ben Aston Mar 05 '20 at 10:23
1 Answers
Is it true that by "it is inherited by all your functions" means each function in a certain module uses 'use strict' inside of itself?
A function will run in strict mode if:
(1) The function is inside an ES6 module (these all run in strict mode regardless), or
(2) There is a proper 'use strict'
directive above the function definition, lexically.
In addition to a few less common instances, such as inside a constructor
.
The way 'use strict'
is inherited lexically works the same way variables can be referenced, and how variable scope works - if any outer block of a function is strict, then the inner function is strict as well. So, for example, with the following code:
'use strict';
function foo() {
function bar() {
function baz() {
}
}
}
No matter what other code you put inside foo
, bar
, and baz
, all of those functions, no matter how they're run, will run in strict mode. If one of these function is called from a source which isn't running in strict mode, the called function will still run in strict mode. For example:
<script>
'use strict';
function foo() {
return function bar() {
return function baz() {
console.log('baz running. strict:', this === undefined);
}
}
}
foo()()();
</script>
<script>
// Non-strict script calling strict function:
foo()()();
</script>

- 356,069
- 52
- 309
- 320