Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!