0

Possible Duplicate:
JavaScript Variable Scope

var flag = false;
if(flag === true)
{
     var you = "great";
}

Variable "you" is initialized with undefined, it shows undefined instead of showing reference error when printed. why?

Community
  • 1
  • 1
Balaji Sivanath
  • 506
  • 4
  • 14

1 Answers1

7

In Javascript, all variables are "hoisted" to the top of the function/scope they're declared in. That is, your code REALLY looks like this to the compiler:

var flag = false;
var you;
if (flag === true)
{
    you = "great"
}
dty
  • 18,795
  • 6
  • 56
  • 82