As a new programmer, I could not figure out the solution to this issue, no matter how many answers I read in this or similar questions. So I'm sharing my solution for others like me arriving here from desperate searching (plus all the related questions looking for a fix are locked and link to this question). So here's an answer to your question that newbies like me can understand how and why to change our code to avoid this issue and have the variables return the values we expect. My issue is that when learning javascript, I assumed every time I wanted to modify a variable I had to start the line with var
like:
var myVariable = 1;
...
var myVariable = myVariable + 3;
when in reality, you should only put var
the first time (when you declare/initialize a variable). All other times after that, you have to start the line with the variable name and drop the var
like:
var myVariable = 1;
...
myVariable = myVariable + 3;
I didn't see an issue with how I was doing it at first, until I started using more functions, then these hoisting issues started to arise and I couldn't understand why, and I just assumed I couldn't use the same variable name across functions, or that I was unable to reference variables outside of the same function, or that I had to force creation/using global variables using some weird method like this.variable or window.variable, or something else weird.
After I deleted all the places I had var
except for the first one per variable, my issues disappeared.
The same thing applies to your code. If you change this:
var x = 'set';
var y = function ()
{
if (!x)
{
var x = 'hoisted';
}
alert(x);
}
y();
(changing var x = 'hoisted';
to x = 'hoisted';
) to this:
var x = 'set';
var y = function ()
{
if (!x)
{
x = 'hoisted';
}
alert(x);
}
y();
then it works as you'd expect, and avoids hoisting.