• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

165
Vistas
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?

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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.

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda