I couldn’t find an exact match on my issue, though many javascript scoping questions do exist. Here is my current code for the question.
var my_var = "blank";
var MyFunc = function() {
my_var = "one";
//var my_var = "two";
}
alert(my_var);
MyFunc();
alert(my_var);
When I run this, I am alerted with “blank” and then “one” as expected. However, if I uncomment that one line, so it looks like this.
var my_var = "blank";
var MyFunc = function() {
my_var = "one";
var my_var = "two";
}
alert(my_var);
MyFunc();
alert(my_var);
I am alerted with “blank” and then “blank”. This is not what I would expect and I find it confusing that adding a line will remove behavior. Can anyone explain what is going on here? I am seeing this behavior in both firefox and safari.
All
varstatements are effectively “hoisted” up to the top of their enclosing function (sort of). Thus, the fact that you’ve gotvar my_varanywhere in that function means that all mentions of “my_var” refer to the local variable.(I said “sort of” because the assignment part of the
varstatement isn’t shifted; just the declaration that the identifier should be a local variable.)