Problem with Variable declaration?

2007-07-31
2013-05-28
  • Peter Sherwood

    Peter Sherwood - 2007-07-31

    Hello,

    If I have the following simple piece of code:

    var x = 1;
    if (x === 1) {
        var URL = 'http://yahoo.com/';
        alert(URL);
    } else {
        var URL = 'http://google.com/';
        alert(URL);
    }

    I get the following warning from Lint:

    JavaScript Lint 0.3.0 (JavaScript-C 1.5 2004-09-24)
    Developed by Matthias Miller (http://www.JavaScriptLint.com)

    test.js
    test.js(6): warning: redeclaration of var URL
        var URL = 'http://google.com/';
    ............^

    0 error(s), 1 warning(s)

    Obviously the variable has not been re-defined as it's at a different scope level. If I comment out the second URL declaration then the value is as expected "undefined".

    Do you think this actually a bug? I use JTest (a java testing programme) and it performs similar checks. Similar java code would not produce a warning due to the level of scope.

    Yes I could use code like the following:

    var x = 1;
    var URL;
    if (x === 1) {
        URL = 'http://yahoo.com/';
        alert(URL);
    } else {
        URL = 'http://google.com/';
        alert(URL);
    }

    However the problem still remains. What do you think?

    regards

    Pete

     
    • Gabriel Barta

      Gabriel Barta - 2007-07-31

      Not sure what you mean when you say "However the problem still remains."  JavaScript Lint will not report an error for your revised code.

      The warning is technically correct - unlike Java, JavaScript does not have block-level scoping so even though each of the variable declarations is written within the braces of the 'if' statement, it is actually a single variable which exists at function-level scope.

       
    • Peter Sherwood

      Peter Sherwood - 2007-07-31

      Gabriel,

      That's a fair reply, I was assuming the scoping was similar to Java. If it is at function level then the message is correct.

      When I meant the problem still remains, I was referring to the warning message when I return the code to block level.

      This piece of code shows it's not a problem.

      if (1 == 1) {
        var newVar = 1;
      }
      if (2 == 2) {
      alert(newVar);
      }

      You get the alert of 1.

      thanks

      Pete

       

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks