4

Why the second function didn't use the "use strict"; mode (it shows me window object in console):

function test() {
    console.log(this);
}
test();   // will be global or window, it's okay

"use strict";

function test2() {
    console.log(this);
}
test2(); // will be global, BUT WHY? It must be undefined, because I have used strict mode!

But if I define strict mode in the body of the second function, all will be as I expect.

function test() {
    console.log(this);
}
test();   // will be global or window

function test2() {
"use strict";
    console.log(this);
}
test2();

My question is simple — why it happens?

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Avernikoz
  • 463
  • 2
  • 5
  • 15
  • 1
    In order to have an effect, `"use strict";` has to be at the very top of a code block or function. If any code is before it, it does nothing. – Pointy Mar 20 '18 at 14:51

2 Answers2

3

See the MDN documentation:

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

and

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.

In your first code block, you have "use strict"; but it isn't the first statement in the script, so it has no effect.

In your second, it is the first statement in a function, so it does.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • would something like `function myFunc(){} 'use strict'; function myOtherFunc() { // my first expressions }` work? – messerbill Mar 20 '18 at 14:57
2

Because "use strict" only has effects if it's the first statement of the current script/function. From the MDN docs :

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.

Community
  • 1
  • 1
Fathy
  • 4,939
  • 1
  • 23
  • 25