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 alert
shows undefined
because the var
statements are hoisted to the top of the enclosing scope, in other words, var
statements and function
declarations are made before the actual code is executed, in the parsing stage.
When your code is executed, is equivalent to:
var a; // declared and initialized with `undefined` before the code executes
alert(a); // undefined
alert(b); // ReferenceError, b is not declared.
a=1;
b=10;
The second alert
doesn't even executes, trying to access b
gives you a ReferenceError
because 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 ReferenceError
exception 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:
var a = 1;
b = 10;
// Similar effect:
window.a; // 1
window.b; // 10
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 var
produces a non-configurable property on the global object (cannot be deleted), e.g.:
delete window.a; // false
delete window.b; // true
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 var
statement will create a local variable, for example:
(function(){
var a = 1;
b = 10;
})();
typeof window.a; // 'undefined', was locally scoped in the above function
typeof window.b; // 'number', leaked, an unintentional global
I would really discourage make assignments to undeclared identifiers, always use var
to declare your variables, moreover, this has been disallowed on ECMAScript 5 Strict Mode, assignments made to undeclared identifiers throw a ReferenceError
:
(function(){'use strict'; b = 10;})(); // throws a ReferenceError
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With