JavaScript variables: Difference between revisions
From MozillaZine Knowledge Base
Jump to navigationJump to search
No edit summary |
mNo edit summary |
||
Line 1: | Line 1: | ||
{{extdev}} | {{extdev}} | ||
==Variables in | ==Variables in JavaScript== | ||
===Scoping=== | ===Scoping=== | ||
<ol> | <ol> | ||
<li>Declare all variables with '''var''' before assigning to them. | <li>Declare all variables with '''var''' before assigning to them. | ||
Assigning to undeclared variable causes a strict | 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" | {| border="1" cellpadding="5" rules="all" | ||
Line 93: | Line 93: | ||
</li></ol> | </li></ol> | ||
[[Category:Development]] [[Category: | [[Category:Development]] [[Category:JavaScript|JavaScript variables]] |
Revision as of 01:46, 26 March 2005
This page is part of the extension development documentation project.
Ask your questions in MozillaZine Forums. Also try browsing example code.
Note: development documentation is in process of being moved to Mozilla Development Center (MDC).
Variables in JavaScript
Scoping
- 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 prefs to see it though) and the variable is put in global scope, which is obviously bad.
Bad example Good example function F() { // generates a strict JS warning x=1; G(); // alerts "2", since x is global. alert(x); } function G() { x=2; }
function F() { var x=1; G(); alert(x); // alerts "1" } function G() { var x=2; }
- Declare each variable exactly once in a function, otherwise you'll get another JS error (redeclaration of var X).
Good example Bad example var i; if(condition) { for(i=0; i<3; i++) dump(i); } else { for(i=2; i>=0; i--) dump(i); }
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); }
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:
Kinda ok Works, but may become unmantainable if(condition) { for(var i=0; i<3; i++) dump(i); } else { for(i=2; i>=0; i--) dump(i); }
if(condition) { for(i=0; i<3; i++) dump(i); } else { // generates a JS warning for(var i=2; i>=0; i--) dump(i); }