Variables defined in global scope with identical names
javascript
Solution
Variable declarations (and function declarations) are hoisted to the top of the scope in which they appear. Assignments happen in place. The code is effectively interpreted like this:
var a;
var a;
a = 'string1';
For example, consider what happens if you declare a variable inside an `if` statement body:
console.log(myVar); //undefined (NOT a reference error)
if (something === somethingElse) {
var myVar = 10;
}
console.log(myVar); //10
Because JavaScript does not have block scope, all declarations in each scope are hoisted to the top of that scope. If you tried to log some variable that was not declared, you would get a reference error. The above example is interpreted like this:
var myVar; //Declaration is hoisted
console.log(myVar);
if (something === somethingElse) {
myVar = 10; //Assignment still happens here
}
console.log(myVar);
So even if the condition evaluates to `false`, the `myVar` variable is still accessible. This is the main reason that JSLint will tell you to move all declarations to the top of the scope in which they appear.
In slightly more detail... this is what the ECMAScript 5 spec has to say (bold emphasis added):
For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do
- Let dn be the Identifier in d.
- Let varAlreadyDeclared be the result of calling env’s HasBinding concrete method passing dn as the argument.
- If varAlreadyDeclared is `false`, then
- Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.
- Call env’s SetMutableBinding concrete method passing dn, `undefined`, and strict as the arguments.
So, if a binding already exists with the identifier we are trying to bind now, nothing happens.
Problem
Can anybody explain, why next js code rises two alert windows with 'string1' text rather than to rise the second with 'undefined' text inside?? If both variables are described in the same scope.. ``` var a = 'string1'; alert(a); var a; alert(a); ``` http://jsfiddle.net/FdRSZ/1/ Thanks