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

159
Vistas
Were I using undefined wrong all these years?

I happened upon something strange (at least to me), and maybe someone can elaborate on this for me:

const a = undefined;
const c = {};

/** this works correctly **/
console.log(a === undefined);

/** this does not throw an exception **/
console.log(c.someProperty === undefined);

/** this throws an exception, why? **/
console.log(b === undefined);

Just is in the example above, why is it, that if I want to check for an objects property, with === undefined which was not defined everything is okay, but as soon as I try to check for a top-level variable for being defined, I am getting an error?

Here's a fiddle.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The ECMAScript Language Specification states that accessing a nonexistent variable throws a ReferenceError (see GetValue) while accessing a nonexistent property results in undefined (see OrdinaryGet).

To check if a global variable is defined, you can use typeof, which does not throw.

console.log(typeof b === 'undefined');

Top-level variables declared with var also exist on the window object, so you can use a property access too.

console.log(window.b === undefined);
about 4 years ago · Juan Pablo Isaza Denunciar

0

The thing is that b is not undefined, it is not even declared.You cannot call a variable that is not declared, be you can with one that is declared but undefined.

const a = undefined;
const b
const c = {};

console.log(a === undefined) //true
console.log(b === undefined) //true
console.log(c.someProperty === undefined) //true
console.log(typeof d === 'undefined') //true, it does not exist

try{
  console.log(d)
} catch (e) {
  console.log('error!')
} //error!
about 4 years ago · Juan Pablo Isaza 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