I found this code:
if (!("aa" in window)) {
alert('oh my god');
var aa = 1;
}
alert("aa" in window);
alert(aa);
This code the second alert is alert true
,but,the third alert is 'undefined',and the alert in the 'if' is not run. Why?
I think the reason is the in
; what is its effect?
I searched on Google, but found nothing, because Google thinks the word ‘in&srquo; is a filter word.
We always use the in
in loops, but, frankly speaking, I use it but don’t really understand it.
Taking the alerts in order:
("aa" in window) === true
so theif
boolean condition is false.JavaScript has function scope and the variable
aa
is "hoisted" up to the top of the scope first, so it is defined."aa" in window
is true because the variable was added to the window object when it was hoisted up. Equivalent to just writing:From the Standard ECMA-262 ECMAScript Language Specification :
So
aa
is undefined since the assignment was never executed.in
checks if property exists inObject
This tests if the
window
object has a property (filled or not) whose key is"aa"
.This operator is very useful because it works even if the value is
undefined
:It also works if the property isn't enumerable :
In your case, there may not be an
aa
value, but if the alert shows you true, the property was added towindow
.MDN reference on in
Note that the
for...in
statement is different in that it doesn't really use thein
operator but is a specific construct.MDN reference on for...in
EDIT : an explanation of your edited question (very different from the first one) :
Your confusion seems to arise from the fact you declared the
var aa = 1;
in a block. You should know that the scope of a variable in JavaScript is either a function of the global scope and that declarations are hoisted. So your code is in fact equivalent to