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 var
statements are effectively "hoisted" up to the top of their enclosing function (sort of). Thus, the fact that you've got var my_var
anywhere 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 var
statement isn't shifted; just the declaration that the identifier should be a local variable.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With