JavaScript variables: Difference between revisions

From MozillaZine Knowledge Base
Jump to navigationJump to search
No edit summary
m (cat redirect)
 
(3 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{extdev}}
See [http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Variables Javscript 1.5 Guide: Variables] at developer.mozilla.org.


==Variables in Javascript==
[[Category:Redirects]]
 
===Scoping===
<ol>
<li>Declare all variables with '''var''' before assigning to them.
Assigning to undeclared variable causes a strict Javascript warning (''"redeclaration of var X"''; you need to set '''javascript.options.strict''' and '''javascript.options.showInConsole''' [[about:config|prefs]] to see it though) and the variable is put in global scope, which is obviously bad.
 
{| border="1" cellpadding="5" rules="all"
! Bad example !! Good example
|-
|
 
<pre>function F() {
  // generates a strict JS warning
  x=1;
  G();
  // alerts "2", since x is global.
  alert(x);
}
 
function G() {
  x=2;
}</pre>
||<pre>function F() {
  var x=1;
  G();
  alert(x); // alerts "1"
}
 
function G() {
  var x=2;
}
 
 
</pre>
|}
</li>
 
 
<li>Declare each variable '''exactly once''' in a function, otherwise you'll get another JS error (''redeclaration of var X'').
 
{| border="1" cellpadding="5" rules="all"
! Good example !! Bad example
|-
|
<pre>var i;
if(condition) {
  for(i=0; i<3; i++)
    dump(i);
} else {
  for(i=2; i>=0; i--)
    dump(i);
}</pre>
||
<pre>if(condition) {
  for(var i=0; i<3; i++)
    dump(i);
} else {
  // generates a JS warning
  for(var i=2; i>=0; i--)
    dump(i);
}</pre>
|}
 
Due to the fact that '''{}''' blocks don't introduce a new variable scope (all variables declarations are effectively moved to the start of the enclosing function by interpreter), the following two examples are also valid:
 
{| border="1" cellpadding="5" rules="all")
! Kinda ok !! Works, but may become [http://www.mindprod.com/unmain.html unmantainable]
|-
|
<pre>if(condition) {
  for(var i=0; i<3; i++)
    dump(i);
} else {
  for(i=2; i>=0; i--)
    dump(i);
}
 
</pre>
||
<pre>if(condition) {
  for(i=0; i<3; i++)
    dump(i);
} else {
  // generates a JS warning
  for(var i=2; i>=0; i--)
    dump(i);
}</pre>
|}
 
</li></ol>
 
[[Category:Development]] [[Category:Javascript|Javascript variables]]

Latest revision as of 20:10, 9 May 2006

See Javscript 1.5 Guide: Variables at developer.mozilla.org.