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

157
Visualizações
How to safely determine whether a block-scoped variable is defined

If the initializer of a const or let variable throws an error, accessing that variable throws a ReferenceError -- even when checking its type via typeof.

// Foo.js
class Foo { constructor() { /* Something goes wrong and throws... */ } }

const gFoo = new Foo(); // Throws an error
// Elsewhere...
console.log(typeof gFoo);  // throws ReferenceError: foo is not defined

Is there another way to test whether gFoo was successfully initialized, or do I have to wrap a typeof check in a try/catch block?

let isInitialized = false;
try {
  if (typeof foo != 'undefined')
    isInitialized = true;
} catch (e) {}  // ugly but it works

Mainly, I'm surprised that typeof can throw a ReferenceError.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

When an error is thrown, the execution of the current function stops (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. At that point, the variable doesn't get initialised, causing the ReferenceError exception.

So to answer your question, whenever you know there are possible errors thrown, make sure to always wrap it within try catch blocks.

With your case above, since the error could happen within the function assigned to foo, you should have the try catch block there; Something like:

const foo = (() => { 
  try {
    // Do whatever
    throw Error();
    // return value to assign to foo
  } catch(err) {
    // Log error for monitoring
    // return undefined
  }
})();

if (foo) { 
  // Do something with foo
} else {
  // Do something if foo errored
}
about 4 years ago · Santiago Trujillo 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