Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda