javascript variable scope in function confusion -


here 2 javascript functions

var = 10; function abcd() {  alert(a);//alerts 10  a=5; } 

and code this

var = 10; function abcd() {  alert(a);//alerts undefined  var a=5; } 

in both function assignment/declaration after alert() call. why alert message 10 , undefined respectively?

that's because variable gets "hoisted" of containing scope interpreter when declare it. code ends being interpreted this:

function abcd() {  var a;  alert(a); //alerts undefined  = 5; } 

to avoid kind of confusion, can follow practices keep things in place, declaring local-scoped (that is, variables declared keyword var inside function scope) variables right in beginning of function.

note that, can read article, happens nested functions aswell.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -