Reputation: 15291
I have a question that is just bothering me. If I declare a var a
and I then try to test it using the "in" operator I get a true result, if I do the same test using the dot notation I get a false result, for example...
var a;
if('a' in window) {
console.log('a in window'); // this is written to the console
}
if (window.a) {
console.log('window.a'); // nothing happening here
}
now I noticed that when I give a a value like so both outputs work... look at this and notice how I check if it doesn't exist:
var a;
if('a' in window) {
console.log('a in window'); // this is written to the console
}
if (!window.a) {
console.log('!window.a'); // this is written to the console
}
a = 1;
if (window.a) {
console.log('window.a'); // this is written to the console
}
So why does the dot notation only work when the variable is assigned a value? A silly question I know but so far I can't get a definite answer!
Upvotes: 2
Views: 87
Reputation: 12437
Go to your console and play like this:
var a;
undefined
'a' in window
true
window.a
undefined
a = 1
1
window.a
1
'a' in window
true
The in
keyword checks if there is a variable in a context. So, an expression using in
, will always return true
or false
based on its existence, not on its value.
The .
notaction access the variable's value in a context. So, an expression using .
, might return any value, including undefined
, if it wasn't.
Now that you know what's being returned for each expression, mix it with what the evaluation done when each value is returned inside an if statement.
As you might know, undefined
will evaluate to false
, and both 1
and true
will evaluate to true, resulting on the behavior you're facing.
Upvotes: 1
Reputation: 580
window.a
is undefined
before you give it a value, and
if (undefined) === if (Boolean(undefined))
Since Boolean(undefined) === false, the console.log
within your if statement is not reached.
Upvotes: 2
Reputation: 788
As Johan pointed out, the check is getting a falsey value.
if ('a' in window) console.log("a exists");
if (window.a) console.log("window.a is a truthy value");
if (!window.a) console.log("window.a is a falsey value");
if (typeof window.a != "undefined") console.log("window.a is not undefined");
Upvotes: 3