Function's scope of variables

function, javascript, scope

Solution

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`, `alert`s it, and then re-sets its value to `9`.

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

Problem

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`?

Original source

Related problems