javascriptuse-strict

Use strict is not working when I call my hoisted function


I have the following code

"use strict";
x = 12;
function myFunction() {

}
myFunction();

so i am using use strict at the top of my script and now I am in strict mode - so I can't have undeclared variable like x

That gives me the following error in my console

Uncaught ReferenceError: x is not defined.

But when I execute this code

myFunction();
"use strict";
x = 12;
function myFunction() {

}

console.log('the script continues...')

I don't get the same error for my undeclared variable x. As you can see the script continues to execute.

Why is that ? Why I don't get the same error when I try to call my hoisted function - so call the function before it is declared ? Why it affects the global scope ?


Solution

  • As it says in MDN's documentation for strict mode, the "use strict"; sequence is only a strict mode directive if it's the first thing in the file other than a comment. With your function call above it, it's no longer the first thing in the file and so it isn't a strict mode directive; instead, it's just a freestanding string literal that nothing uses.

    Since your code isn't in strict mode, x = 12; is assigning a value to an undeclared identifier, which (in loose mode) creates an implicit global. (More in my ancient post on my anemic old blog: The Horror of Implicit Globals.) This is one of the many reasons using strict mode is a Good Thing™, because with it assigning to an undeclared identifier is the error it always should have been.


    Side note: Another way to use strict mode is to use native modules rather than the "use strict";. Modules, like nearly all new scopes in JavaScript since ES2015, are strict by default (and have other benefits, like their own scope and the ability to declare dependencies between them).