3

I execute function like this:

var a = 123;
function f() { 
  alert(a);
  var a = 9;
} 
f();

the result is undefined, why this happened? Why it's not 123?

2

2 Answers 2

8

Your function is actually compiled as:

function f() {
  var a; 
  alert(a);
  a = 9;
} 

because of variable hoisting: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var#var_hoisting

So your function redeclares a as a local variable with the value as undefined, alerts it, and then re-sets its value to 9.

At the time of the alert, its value is undefined because of the hoisting.

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

4 Comments

but if I remove the var a = 9;, the alert could show correctly 123, why it doesn't redeclares a?
@hh54188 If you remove var a = 9;, then there is no redeclaration...you removed it...all your function will be is alert(a);. So it looks up the scope chain and finds a in the global scope as 123, so it's evaluated as 123.
but the redeclare was happened after the alert, so this means the variable declare is doesn't matter with exetute order?
@hh54188 Right, but if you read my answer, it explains that the variable declaration was hoisted (read the website link I provided too). Technically, your function is technically executed as the function I included in my answer, because of hoisting. So a is technically redefined at the beginning of the function (before the alert)
0

If you declare a in a function syntax again that becomes a new variable. If you want to use the previous value 123 then you should not have included the var a = 9 statement, since it creates a new variable. This may explain in detail : What is the scope of variables in JavaScript?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.