Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why this javascript has no error in strict mode

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???

1 Answers

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.

like image 180
melpomene Avatar answered Jul 29 '26 04:07

melpomene