Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a property exists in "window" fails if "window." is not prepended

Tags:

javascript

I want to check if a property exists in window, so I did this:

This code works:

if (window.foo) {
    alert("exists");
}
else {
    alert("doesn't exist");
}

Output:

doesn't exist

I thought the next code should work too because as far as I know when you define variables and you are not inside a function they are created as a property of the "window" object so this should be equivalent:

if (foo) { //it fails here "foo is not defined"
    alert("exists");
} else {
    alert("doesn't exist");
}

To my surprise it didn't work. My question is why it doesn't work if I don't prepend window?

like image 476
Alfredo Osorio Avatar asked Mar 23 '23 07:03

Alfredo Osorio


1 Answers

The first version is property access, it can't find the property so it returns undefined. The second is trying to access undefined variable .

Use what elclanrs suggested:

if(typeof foo === "undefined"){
    alert("exists");
} else {
    alert("doesn't exist");
}

Why?

This is because of the GetValue specified in the language specification.

.3. If IsUnresolvableReference(V), throw a ReferenceError exception.

This is what happens in the if(foo) case, since foo was not defined before.

On the other hand, if its an object the following happens:

  1. Let base be the result of calling GetBase(V).
  2. Let O be ToObject(base).
  3. Let desc be the result of calling the [[GetProperty]] internal method of O with property name P.
  4. If desc is undefined, return undefined.

So window.foo returns the primitive language value undefined which is falsy.

like image 159
Benjamin Gruenbaum Avatar answered Apr 07 '23 06:04

Benjamin Gruenbaum