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?

Zong
  • 6,160
  • 5
  • 32
  • 46
hh54188
  • 14,887
  • 32
  • 113
  • 184
  • 2
    http://stackoverflow.com/questions/500431/javascript-variable-scope What happens is the interpreter knows that `a` is defined within the scope of `f`, just not at the point where you call `alert()`. Hence `undefined`. – maksimov Apr 17 '13 at 16:07
  • possible duplicate of [javascript variable is undefined](http://stackoverflow.com/questions/11963240/javascript-variable-is-undefined) – Felix Kling Apr 17 '13 at 16:10

2 Answers2

9

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.

Ian
  • 50,146
  • 13
  • 101
  • 111
  • but if I remove the `var a = 9;`, the alert could show correctly `123`, why it doesn't redeclares `a`? – hh54188 Apr 17 '13 at 16:10
  • @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`. – Ian Apr 17 '13 at 16:12
  • but the redeclare was happened after the `alert`, so this means the variable declare is doesn't matter with exetute order? – hh54188 Apr 17 '13 at 16:17
  • 1
    @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`) – Ian Apr 17 '13 at 16:22
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?

Community
  • 1
  • 1
Gowtham
  • 11,853
  • 12
  • 43
  • 64