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);
Thanks
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:
For example, consider what happens if you declare a variable inside an
ifstatement body: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:
So even if the condition evaluates to
false, themyVarvariable 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):
So, if a binding already exists with the identifier we are trying to bind now, nothing happens.