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?
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");
}
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:
- Let base be the result of calling GetBase(V).
- Let O be ToObject(base).
- Let desc be the result of calling the [[GetProperty]] internal method of O with property name P.
- If desc is undefined, return undefined.
So window.foo
returns the primitive language value undefined
which is falsy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With