Hint: Variables scope “Javascript”

written by Amr ElGarhy on Monday, March 02 2009





All variables declared in a function are defined throughout the function
var scope = "global";
function f( ) {
alert(scope); // Displays "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined everywhere
alert(scope); // Displays "local"
}
f( );
 
So previous function equal the following one:
function f( ) {
var scope; // Local variable is declared at the start of the function
alert(scope); // It exists here, but still has "undefined" value
scope = "local"; // Now we initialize it and give it a value
alert(scope); // And here it has a value
}
This example illustrates why it is good programming practice to place all your variable declarations together at the start of any function.

kick it on DotNetKicks.com

Similar Posts

  1. Developers/Job Seekers, did you consider Stackoverflow?
  2. HOW TO TELL WHEN IMAGES HAVE LOADED
  3. Flash Javascript communication first look

Comments

  • CodeGuru on on 3.03.2009 at 11:40 AM

    CodeGuru avatar

    Nice hint, didn't know about before.

Post a comment

Options:

Size

Colors