Your loop outputs 0,1,2,3
so you're working under some sort of false assumption about what your code does. See http://jsfiddle.net/jfriend00/9uo5g5fo/ for a running demo to see the actual output.
Local variables that are declared but not initialized are still local variables. They only become global variables if you are not running in strict mode and if you do not declare them before using them (which is a bad practice to follow). I'm not sure why you're asking about this because it doesn't effect your current code.
The current version of Javascript (ES5) has only function scope for variables so all variable declarations within a function are hoisted to the top of the function or scope so your code:
for (i = 0; i < 4; i++) {
var g=0;
if (g === undefined) {
g = 0;
} else {
g = g + i;
alert(g);
}
}
is equivalent to this:
var g;
for (i = 0; i < 4; i++) {
g=0;
if (g === undefined) {
g = 0;
} else {
g = g + i;
alert(g);
}
}
The reason your code outputs 0,1,2,3
is because g
will be set to 0
at the start of every iteration of your for
loop and thus the first if
will never be satisfied so the else
will always execute which will cause g = g + i
to be executed. But, since g
is always 0
, that will be like setting g = i
, so your alert(g)
will just be showing the value of i
.
Your code is essentially just this:
for (i = 0; i < 4; i++) {
alert(i);
}
FYI, the next version of Javascript (ES6) offers the let
keyword so you can declare variables with block scope, but that version is only partially implemented in some of the latest versions of browsers so isn't generally available for widespread browser use yet. It can be used in some non-browser uses of Javascript.