javascriptstrictuse-strict

"use strict" in the middle of the program


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?


Solution

  • 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.