function - Why JavaScript declared variable is in the global object before initialization? -
i've stumbled upon javascript variable behavior not explain.
according js docs on var keyword :
the scope of variable declared var enclosing function or, variables declared outside function, global scope (which bound global object).
also known global variables become properties of global object - 'window' in browser environments , 'global' in node.js means if variable declared 'var' keyword inside function becomes local , not global object.
this example proves it:
(function(){ var t = 1; console.log(t in window, t); // outputs: false 1 }());
so far good. if variable not initialized become property of window object despite fact in function scope.
(function(){ var t; console.log(t in window, t); // outputs: true undefined }());
why happen ? can learn details of behavior ? regular tutorials don't seem cover this.
thanks in advance.
[edit]: pointy clear scope works expected. had wrong understanding of 'in' operator behavior. according 'in' docs coerces left hand operand number or string , looks such index or property name in right hand object. in example 1 equal to
'1' in window
which false
and in example 2 was
'undefined' in window
which true.
the issue test code using in
operator erroneously. it's testing whether name "undefined" defined in window
, not "t". why? because left-hand operand of in
coerced string. because "t" undefined
, it's coerced string "undefined", , indeed property name present in global context.
change test to
console.log("t" in window, t);
Comments
Post a Comment