Mega Code Archive

 
Categories / JavaScript Tutorial / Language Basics
 

Variable Scope

A variable can be either global or local in JavaScript. All variables are global unless they are declared in a function. Variables declared in a function is local to that function. It is possible for two variables with the same name to exist if one is global and the other is local. When accessing the variable within the function, you are accessing the local variable. If the variable is accessed outside the function, the global variable is used. Always use the var keyword to declare local variables in functions. Without var, JavaScript will create a global variable. <HTML> <SCRIPT LANGUAGE="JavaScript"> <!--     //Initialize global variables     color = "global";     var size = 15;     function myFunction() {       //Declare and set variables inside function       color = "set in a function";       price = "1111";       var size = 17;       document.write("The ",size," inch ",color);       document.write(" price is ",price);     }     myFunction();     document.write("<BR>The ",size," inch ",color);     document.write(" price is ",price); --> </SCRIPT> </HTML>