Reputation: 8240
I have got a simple program which I am running first time in a browser. I am on line 6. When I am trying to find out values of a, b - the browser responds with value 'undefined'. But when I am trying to find out value of c, which of course is not present it gives me an error.
My Question is when I am debugging at line 6 - the status of b & c must be same - either both 'undefined' or both 'giving error', because for the program at line no 6, a exists - but both - b & c are ghosts at this state of program, then how is it giving b as undefined and c as error (which of coarse is correct). But, when did the program found out which variables am I using and which not, when I am still in mid, at first half of program, running it first time.
Upvotes: 0
Views: 45
Reputation: 816472
JavaScripts hoists variable declarations. That means that even before the code is executed, JavaScript will create bindings in the current environment for every variable declaration in the source and initializes them with undefined
.
You can think of the evaluation order as:
var a;
var b;
> a = ...;
b = ...;
where you are breaking on the third line.
There is no binding c
in the current environment which is why it throws a ReferenceError.
See also Javascript function scoping and hoisting and many others.
Upvotes: 1
Reputation: 3202
that is because hoisting.
as your variables a and b are declared in the script,js compiler will move them to top of the script while executing.
your code
var a=['apple','mango'];
var b=[{color:'red'}];
while executing compiler moves the declarations to top of the script.
var a;
var b;
a=['apple','mango'];
b=[{color:'red'}];
so when you access a
or b
,you will see undefined
as their value.but still c
is not declared.so you will get exception
Upvotes: 1