JavaScript: Initializing variable in function -
a basic question here. can see going on can't understand why work way.
a = false; var k = function() { console.log(a); var = true console.log(a); }();
i expect log read "false, true" "a" undefined @ first. can please elaborate why this.
ps. i'm not looking answer telling me should do, i'm looking explanation of inner workings of piece of javascript.
thanks in advance
this because javascript scoping works called "hoisting". when parser reads javascript function, goes through , finds variables defined in scope (using var
) keyword (remember type of scope in javascript function scope). puts them @ top of function.
so parser interprets code follows:
a = false; var k = (function() { var a; console.log(a); = true console.log(a); }());
(nb have corrected function call doesn't return syntax error.)
obviously sets a
undefined
before first console.log
.
every definition of variable declaration of variable @ top of scope , assignment @ place definition is.
Comments
Post a Comment