Comments:

The reason is that var, const, and function statements are "hoisted" to the top of the containing block. Although the actual initialization will not happen until line two of showScope, "scope1" is defined as a local variable right from the start, shadowing the global "scope1". This is equivilant to...

function showScope()
{
var scope;
alert("The value of scope1 is" + \n + scope1);
scope1 = "SCOPE1";
alert("The value of scope1 is" + \n + scope1);
}

You may notice the effect of function hoisting when you have a situation like...

funciton foo() { something(); }

x += 1;

function bar() { somethingElse(); }

...where x is not defined. This will generate the runtime error "x is not defined", but the script will appear to "continue" on to define bar() despite the error.

Posted by rginda at February 25, 2003 10:47 PM

Actually, it'll give you a syntax error, because the \n needs to be inside quotes. I think what you meant is:

alert("The value of scope1 is \n" + scope1);

Posted by Joe Grossberg at February 27, 2003 12:56 PM
Post a comment