12

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?

Sentropie
  • 249
  • 1
  • 4
  • 14

1 Answers1

18

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 3
    Is there any performance cost to redefining a variable? I do like declaring my local variables inside my if, for, while, etc. to keep the code tidy and readable. This is solely by personal taste (I know the scope of the variable is within the function), and I'd like to make sure it doesn't have a negative impact on performances. – Gyum Fox May 17 '13 at 08:58
  • 5
    Here is the answer to my question: http://jsfiddle.net/U5Zdv/ => it makes absolutely no difference in terms of performance on IE10 – Gyum Fox May 17 '13 at 10:30
  • 1
    @GyumFox, It may not make a difference in performance but it is a best practice to manually "hoist" your variables at the top of their functions. This allows you & your collaborators to easily identify the scope of your variables. If you are using variables that only need to be accessed in your if, for, & while loops, you should use `let` & `const` variables since they have block scope. They will not get hoisted, you will have better track of their scope, & they will not pollute the global scope. You may already know this at this point but I figure its worth mentioning in case others see this. – Darryl Mendonez Apr 26 '20 at 13:35