I have a rather general question regarding JavaScript and local variables. My question is what is the difference between the following and if there is any:
function bla
{
var a = 2; // local variable
a = 3; // the local variable a gets a new value
// Would do the following line anything different
// (than simply asigning this value?)
var a = 4;
}
I suppose I won't get two local variables named a. In other languages this is even an error. So is there any use for this?
I have a rather general question regarding JavaScript and local variables. My question is what is the difference between the following and if there is any:
function bla
{
var a = 2; // local variable
a = 3; // the local variable a gets a new value
// Would do the following line anything different
// (than simply asigning this value?)
var a = 4;
}
I suppose I won't get two local variables named a. In other languages this is even an error. So is there any use for this?
Share Improve this question asked Feb 16, 2012 at 12:47 SentropieSentropie 2591 gold badge4 silver badges14 bronze badges1 Answer
Reset to default 18Any use of var
within a function is hoisted. Subsequent uses on the same variable in the same scope have no effect.
It has exactly the same meaning as a = 4;
alone.