Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!