See my example code below
<script>
alert(a); // undefined
alert(b); // It is Error, b is not defined.
var a=1;
b=10;
</script>
When both variable a and b are in global scope, why I am getting error message for b. But there is no error message for variable a ? what is the reason ?
can anyone please explain me ?
The first
alertshowsundefinedbecause thevarstatements are hoisted to the top of the enclosing scope, in other words,varstatements andfunctiondeclarations are made before the actual code is executed, in the parsing stage.When your code is executed, is equivalent to:
The second
alertdoesn’t even executes, trying to accessbgives you aReferenceErrorbecause you never declared it, and you are trying to access it.That’s how the identifier resolution process works in Javascript, if an identifier is not found in all the scope chain, a
ReferenceErrorexception is thrown.Also, you should know that assigning an identifier without declaring it first (as
b = 10) does not technically declares a variable, even in the global scope, the effect may be similar (and it seems to work), at the end the identifier ends as a property of the global object, for example:But this is just due the fact that the global object is the top-most environment record of the scope chain.
Another difference between the two above is that the identifier declared with
varproduces a non-configurable property on the global object (cannot be deleted), e.g.:Also, if you are in the scope of a function, and you make an assignment to an undeclared identifier, it will end up being a property of the global object, just like in the above example, whereas the
varstatement will create a local variable, for example:I would really discourage make assignments to undeclared identifiers, always use
varto declare your variables, moreover, this has been disallowed on ECMAScript 5 Strict Mode, assignments made to undeclared identifiers throw aReferenceError: