Javascript variables scope
A variable can be defined as a segment of memory which holds some kind of value. The programmer can reference that segment of memory by using the name of the variable in order to assign it a value or to read it and use it.
In Javascript, the scope of the variable is the area of the script where that variable is valid to be used. The scope of the global variable is the entire script. That means you can access it anywhere between the <script> and </script> tags and in other scripts that are executed after the variable definition.
A global variable is a variable defined in the main part of the script (not inside a function for instance). It makes no difference if you define it using the keyword var or without it. It does make all the difference in the world if you use it inside a function.
A local variable is a variable that is defined inside a function. It is only available to be used inside that function. Javascript allows you to use the same name for a global variable and for a local one, but when used inside that function, the local variable will be evaluated. A local variable is defined only by using the keyword var. If the keyword is omitted, the variable is defined as global.
Local variables are temporary. Global variables are permanent. Permanent variables exist throughout the execution of all the scripts, until being discarded when the page unloads. Temporary variables are allocated on the stack every time the function is called and deallocated when the execution of the function ends. Large local chunk of data causes the stack to overflow, so data structures like large arrays declared inside a function (as local) or passed to the function (as arguments) should be avoided. Use global variables for such tasks.
Variables in Javascript can only be of 4 types: number (there is no distinction between integer and real-valued numbers), string, Boolean and null values. Remember that Javascript is a “loosely typed language”, which means the type of the variable is not declared explicitly. Javascript implicitly determines the type of the variable based on the initial value that is assigned to it.
The null value is automatically converted to the initial values of other data types once that variable is initialized to a different type – when used as a number, it becomes 0, when used as a string it becomes “” and when used as a boolean it becomes false.
Data types are automatically converted as needed throughout the execution of the script. For instance, when an expression containing a number and a string (like a sum) is evaluated, the value returned is a string. Also, keep in mind that in Javascript evaluation is done from left to right and only paranthesys can change the order of the evaluation:
10 + 10 will return 20
10 + “10″ will return “1010″
10 + 10 + “10″ will return “2010″.




