简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM