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

225
Visualizações
Javascript checking if window is undefined

I was writing a check to see if my code is running on the browser and I first tried the following 2 approaches:

if (window) {
    // do browser stuff
}


if (window !== undefined) {
    // do browser stuff
}

When I try using this code, I get an error saying window is not defined. However, when I try the following approach it works:

if (typeof window !== 'undefined') {
    // do browser stuff
}

Why do the first 2 if statements throw an error but the third doesn't?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So the identity checks window !== undefined and window throw an error because window was not defined. That's exactly what the error is telling you when you try it in the console:

VM49:1 Uncaught ReferenceError: iDoNotExist is not defined

I think the misconception that this should work comes from how the identity check is usually used. In functions we often perform this kind of check on the input parameter.

const myFunction = (inputParam) => {
   if (inputParam){
      console.log(inputParam)
   } else {
      console.log("invalid parameter")
   }
}

myFunction("hello")
// 'hello'

myFunction()
// 'undefined'

myFunction(null)
// 'undefined'

myFunction(undefined)
// 'undefined'

The typeof-operator on the other hand returns the type of its operand as a string. Since undefined is one of JavaScripts types the expression does not throw an error and returns 'undefined' instead.

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