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???
  • 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 – Jaromanda X Jun 12 '18 at 03:18
  • Take a look at this to know how to use "use strict".https://www.w3schools.com/js/js_strict.asp – Terry Wei Jun 12 '18 at 03:22
  • Possible duplicate of [What does "use strict" do in JavaScript, and what is the reasoning behind it?](https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it) – 4castle Jun 12 '18 at 03:24
  • oic, thanks @JaromandaX. –  Jun 12 '18 at 03:34

1 Answers1

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.

melpomene
  • 84,125
  • 8
  • 85
  • 148