web - scope of the variable in JavaScript -
this question has answer here:
function foo(a) { function a() { return 8; } return a(); y = 9; } console.log(foo() + " " + y); this gives undefined error variable y.
function foo(a) { y = 9; function a() { return 8; } return a(); } console.log(foo() + " " + y); this prints 8 9 in browser console.
if declare variable without var keyword becomes global variable.
why first function not follow idea?
it's because in first example, have return statement before y = 9 , assignment never reached, leaving undefined.
Comments
Post a Comment