docs:programming:javascript:var

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
docs:programming:javascript:var [2007/11/11 13:53] – created billhdocs:programming:javascript:var [2008/08/03 00:25] (current) – external edit 127.0.0.1
Line 24: Line 24:
 for(var i in o) document.write(i, "<br>"); for(var i in o) document.write(i, "<br>");
 </code> </code>
 +
 +===== Global, Local, Implicit and Scope =====
 +If you attempt to read the value of an undeclared variable, JavaScript generates an error.  If you assign a value to a variable that you have not declared with var, JavaScript implicitly declares that variable for you.  Note, however, that implicitly declared variables are always created as global variables, even if they are used within the body of a function.  To prevent the creation of a global variable (or the use of an existing global variable) when you meant to create a local variable to use within a single function, you must always use the var statement within function bodies.  It's sest to use var for all variables, whether global or local.
 +
 +Global variables are accessible everywhere, whereas local variables are only accessible within the current function scope.  JavaScript does not have block scope, but it does maintain scope throughout a function, even if there are nested functions, etc...  Inside a function block, local variables are defined with the var keyword.  When the function ends, the variables are no longer available.  If the var keyword was not used, the variables will be implicitly declared and made global.
 +
 +A local variable takes precedence over a global variable of the same name.  Be careful and understand that you can hide global variables within a function if using var on a variable of the same name as an existing global variable, and be extra careful because you can overwrite a global variable value if you decide not to use var.  The best way to avoid problems is simple:  DECLARE ALL VARIABLES WITH var.
 +
 +===== Notes =====
 +  * Variables declared with var are //permanent//: attempting to delete them with the delete operator causes an error.
 +  * It is legal and harmless to declare a variable more than once with the var statement.
  • docs/programming/javascript/var.1194814384.txt.gz
  • Last modified: 2008/08/03 00:25
  • (external edit)