0

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.

enter image description here

Deadpool
  • 7,811
  • 9
  • 44
  • 88

2 Answers2

1

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.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Any standard link for documentation ? – Deadpool Mar 10 '16 at 06:33
  • If you want to read the spec: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-globaldeclarationinstantiation step 16 for the global environment and http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation step 27 and 28 for functions. Otherwise, various sources provide easier to understand explanations, e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting, or https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch4.md, but they are not "standard". – Felix Kling Mar 10 '16 at 06:38
1

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

Pavan Teja
  • 3,192
  • 1
  • 15
  • 22