Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefining a local variable with var in JavaScript

Tags:

javascript

var

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?

like image 687
Sentropie Avatar asked Feb 16 '12 12:02

Sentropie


1 Answers

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

like image 162
Quentin Avatar answered Oct 22 '22 20:10

Quentin