0

I'm just wondering what exactly happens (internally) if you try to initialize a variable multiple times.

For example:

var x = -5;

if(x < 0) {
    var x = 5;
}

I understand that the final result will be x = 5 but will this cause the browser to destroy the variable and re-initiate it?

Adonis K. Kakoulidis
  • 4,951
  • 6
  • 34
  • 43
  • 1
    @OliCharlesworth — Not a duplicate. That discusses variables in different functions. This question is about the use of `var` multiple times in the same function. – Quentin Dec 25 '13 at 23:37
  • @OliCharlesworth That's not the same. The first initiation is tied to window, the second one is tied in the function. – Adonis K. Kakoulidis Dec 25 '13 at 23:38
  • Two bites and the cherry—the question in the subject is different to the question in the body. – RobG Dec 25 '13 at 23:57

2 Answers2

5

No.

var gets hoisted anyway, so it doesn't matter where it appears in the function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I'm just curious, does ECMA standard say anything about double declaration? – Teemu Dec 25 '13 at 23:50
  • [ish](http://www.ecma-international.org/ecma-262/5.1/#sec-10.5). It says to only do something if it hasn't been declared already. – Quentin Dec 25 '13 at 23:56
4

When a function is abeout to be executed, all variable and function declarations are evaluated. This is the step for the variable declarations:

8. For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do

   a. Let dn be the Identifier in d.

   b. Let varAlreadyDeclared be the result of calling env’s HasBinding concrete method passing dn as the argument.

   c. If varAlreadyDeclared is false, then
      i. Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.
      ii. Call env’s SetMutableBinding concrete method passing dn, undefined, and strict as the arguments.

That's it, there is no "else" clause for varAlreadyDeclared being true. Nothing happens when the variable was already declared.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143