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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Any standard link for documentation ?
If you want to read the spec: ecma-international.org/ecma-262/6.0/… step 16 for the global environment and ecma-international.org/ecma-262/6.0/… step 27 and 28 for functions. Otherwise, various sources provide easier to understand explanations, e.g. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, or github.com/getify/You-Dont-Know-JS/blob/master/…, but they are not "standard".
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.