JavaScript variables

From MozillaZine Knowledge Base
Revision as of 01:46, 26 March 2005 by Fatalis (talk | contribs)
Jump to navigationJump to search

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

  1. 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;
    }
    
    
    
  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);
    }