Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Scoping Confusion

Tags:

javascript

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.

like image 231
Ty. Avatar asked Oct 03 '11 15:10

Ty.


1 Answers

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.)

like image 194
Pointy Avatar answered Oct 01 '22 11:10

Pointy