Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda