-3

In my code I keep getting ReferenceError: window is not defined even though I check for window.

my code:

var isReferrerArgonauts = window && window.document.referrer.indexOf('argonauts-bd.com') !== -1;

for sanity checking I even tried putting it window in an if statement and even checking that window !== undefined but all to no avail.

What am I doing wrong?

ThinkBonobo
  • 15,487
  • 9
  • 65
  • 80
  • 1
    Possible duplicate of [How to check for "undefined" in JavaScript?](https://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript) – str Oct 31 '18 at 15:39
  • 1
    The answer is a duplicate in the sense that that's how you solve the problem but I didn't know that was a problem until I knew the answer. This question would help people who get this error but don't know that the problem is that you can't expect a variable to return undefined if it is not first assigned. – ThinkBonobo Oct 31 '18 at 20:03

1 Answers1

3

The problem was how I was investigating that window was undefined. In javascript if it is an object property, you can check for undefined in the ways that were mentioned in the question.

However, variables such as window don't act as properties, you would need to investigate using typeof such as the following:

    const isReferrerArgonauts = (typeof window !== 'undefined') && (window.document.referrer.indexOf('argonauts-bd.com') !== -1);

Typeof guarantees a string response and you will not get the reference error.

ThinkBonobo
  • 15,487
  • 9
  • 65
  • 80