JavaScript Strict Mode生效场景咨询:代码块中为何未触发?
Great question—your test cases perfectly highlight a common gotcha with JavaScript's Strict Mode! Let’s break down exactly how it works, using your examples as context.
First, the Core Rule
Strict Mode in JavaScript is scoped to entire scripts or individual functions—it does not apply to arbitrary block-level scopes (like the {} you used in your second test). That’s why your two tests had such different results.
Your First Test: Strict Mode Works in a Function
In your first example, you placed "use strict"; at the top of a function body. This activates Strict Mode for the entire function:
function test() { "use strict"; a = 4; // Throws ReferenceError (strict mode disallows undeclared variables) alert(a); // This line never runs because the error stops execution }
As you expected, since a isn’t declared with var, let, or const, Strict Mode throws an error immediately, so the alert never fires. This is exactly how Strict Mode is supposed to behave here.
Your Second Test: Strict Mode Fails in a Block
In your second example, you wrapped code in a standalone {} block and added "use strict"; inside it. This doesn’t activate Strict Mode at all:
{ "use strict"; // This declaration is ignored—Strict Mode doesn't apply to plain blocks a = 4; // Non-strict mode: automatically creates a global variable `a` alert(a); // Runs normally, pops up "4" }
Plain blocks (not part of functions, loops, or conditionals in a way that creates a variable scope) don’t trigger Strict Mode. The "use strict"; here is just a string literal with no effect, so your code runs in normal, non-strict mode—where undeclared variable assignments create global variables instead of throwing errors.
When Strict Mode Does Take Effect
- Global script scope: Add
"use strict";as the very first line of a script file (before any other code), and the entire script runs in Strict Mode. - Function scope: Add
"use strict";as the first line inside a function body (before any other statements in the function), and that entire function runs in Strict Mode. - ES6 Modules: All ES6 modules (using
import/exportsyntax) run in Strict Mode by default—you don’t need to add the declaration at all.
When Strict Mode Does NOT Take Effect
- Plain block scopes: Any
{}block that’s not a function, module, or class will ignore a"use strict";declaration inside it. - Non-top placement: If you put
"use strict";after other code in a script or function, it won’t activate Strict Mode for that scope. - Nested inside non-strict code: If a function is inside a non-strict script, you still need to add
"use strict";to the function to enable it there (it doesn’t inherit strictness from outer scopes).
内容的提问来源于stack exchange,提问作者Bran Tran

