I have trouble understanding JavaScript function level scope, as a C# programmer it looks wired to me, I will try to explain it through code:
CODE#1
//Problem
//if same named variable (as in global scope) is used inside function scope,
//then variable defined inside function will be used,global one will be shadowed
var a = 123;
function func() {
alert(a); //returns undefined,why not just return 123 ?
//how come js knew that there is variable 'a' will be defined and used in
//this function scope ,js is interpreter based ?
var a = 1; //a is defined inside function
alert(a); //returns 1
}
func();
CODE#2
//when a variable(inside function) not named as same as the global,
//then it can be used inside function,and global variable is not shadowed
var k = 123;
function func2() {
alert(k); //returns 123 ,why not 'undefined'
var c = 1;
alert(c); //returns 1
}
func2();
So my questions are
in CODE#1 why first time
aisundefined,why not it's just return123? And how comejsknew that there is variable 'a' will be defined and used in this function scope,jsis interpreter based?in CODE#2 why not
kis 'undefined'?
hoistinginjsadequatelygood.com/JavaScript-Scoping-and-Hoisting.htmlletinstead ofvar.it does the same thing, andlethas block level scope