Home > database >  Javascript checking if window is undefined
Javascript checking if window is undefined

Time:04-29

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?

CodePudding user response:

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.

  • Related