3

it is weird that. where "use strict" I place will have different result.
My node version is v9.9.0
I don't understand, would somebody help me

"use strict"; function tryFunction() { var tryValue = 123; return tryValue; } if (true) { testvar = 123; // ReferenceError: testvar is not defined }

function tryFunction() { var tryValue = 123; return tryValue; } "use strict"; if (true) { testvar = 123; } // no errors???

function tryFunction() { var tryValue = 123; return tryValue; } if (true) { "use strict"; testvar = 123; } // no errors???

4
  • 10
    "strict mode" only gets triggered at the "top" of a script file, or "top" of a function ... your second two code snippets don't meet this criteria Commented Jun 12, 2018 at 3:18
  • Take a look at this to know how to use "use strict".w3schools.com/js/js_strict.asp Commented Jun 12, 2018 at 3:22
  • Possible duplicate of What does "use strict" do in JavaScript, and what is the reasoning behind it? Commented Jun 12, 2018 at 3:24
  • oic, thanks @JaromandaX. Commented Jun 12, 2018 at 3:34

1 Answer 1

1

See e.g. the MDN documentation for strict mode:

Strict mode applies to entire scripts or to individual functions.

[...]

To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

[...]

Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements.

(Emphasis mine.)

If "use strict"; appears in the middle of a file or block, it has no effect and is ignored as any other string literal would be.

Sign up to request clarification or add additional context in comments.

Comments