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

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

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 Relatório

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