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

156
Views
Cómo determinar de forma segura si una variable de ámbito de bloque está definida

Si el inicializador de una variable const o let arroja un error, acceder a esa variable arroja un ReferenceError , incluso cuando se verifica su tipo a través de 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

¿Hay otra forma de probar si gFoo se inicializó con éxito, o tengo que envolver un typeof check en un bloque try / catch ?

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

Principalmente, me sorprende que typeof pueda arrojar un ReferenceError .

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Cuando se lanza un error, la ejecución de la función actual se detiene (las declaraciones posteriores al lanzamiento no se ejecutarán) y el control pasará al primer bloque catch en la pila de llamadas. En ese momento, la variable no se inicializa, lo que genera la excepción ReferenceError.

Entonces, para responder a su pregunta, siempre que sepa que hay posibles errores, asegúrese de envolverlo siempre dentro de los bloques try catch.

Con su caso anterior, dado que el error podría ocurrir dentro de la función asignada a foo, debería tener el bloque try catch allí; Algo como:

 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 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!