Variables defined in the global scope with the same name

Can someone explain why the following js code brings up two warning windows with the text 'string1' instead of raising the second with the text undefined inside? If both variables are described in the same scope.

var a = 'string1';  
alert(a);  
var a;  
alert(a);​

http://jsfiddle.net/FdRSZ/1/

thank

+5
source share
4 answers

Variable declarations (and function declarations) go up at the top of the area in which they appear. Assignments take place on site. The code is effectively interpreted as follows:

var a;
var a;
a = 'string1';

For example, consider what happens if you declare a variable inside the statement body if:

console.log(myVar); //undefined (NOT a reference error)
if (something === somethingElse) {
    var myVar = 10;
}
console.log(myVar); //10

JavaScript , . , , . :

var myVar; //Declaration is hoisted
console.log(myVar);
if (something === somethingElse) {
    myVar = 10; //Assignment still happens here
}
console.log(myVar);

, false, myVar . , JSLint , .


... ECMAScript 5 ( ):

VariableDeclaration VariableDeclarationNoIn d , do

  • dn - d.
  • varAlreadyDeclared - envs HasBinding , dn .
  • varAlreadyDeclared false,
    • envs CreateMutableBinding , dn configurableBindings .
    • envs SetMutableBinding , dn, undefined .

, , , .

+6

, JavaScript -, . , JS :

var a; // hoisted -> declared on top

a = 'string1';
alert(a);
alert(a);

# Bad JavaScript Habits , JavaScript.

+4

This is because the second is var anot a separate variable declaration. As for the javascript interpreter, this is the same as the first.

+3
source

varmeans "The scope of this variable for this function" and not "Set the value of this variable to undefined."

If a variable is already bound to a function, then it var foomeans the same thing as justfoo

+3
source

All Articles