Loading ...
Sorry, an error occurred while loading the content.

546Re: Undefined variable

Expand Messages
  • crlender
    May 28, 2009
    • 0 Attachment
      --- In jslint_com@yahoogroups.com, "sandyhead25" <austin.cheney@...> wrote:
      > The most correct answer is not test to see if a variable is
      > defined.

      You mean declared, not defined (big difference).

      > The way to ensure this is never a problem is to define your
      > variables first according to the scope you desire. If that is
      > global then the first thing in your code should be:
      > var a, b, c, d, other_var_name;

      Actually, the ECMAScript specs say that an implementation will
      see an identifier as a local variable if it is declared *anywhere*
      in the current scope - not just at the beginning. Look here:

      var foo = "hey";
      function blarg () {
      console.log(foo); // calls log() with an *undefined* value...
      if (false) {
      var foo = "baz"; // ...because it's declared as local here
      console.log(foo); // still undefined
      foo = "qux";
      console.log(foo); // ah, now it's declared *and* defined

      This function has a local variable named "foo". It doesn't matter if
      the contents of the if-branch are ever reached. What JSLint is
      complaining about in this case is that we used foo _before_ it was
      declared. This is perfectly legal in JavaScript, but not considered
      good style. So, what you want to do in this case is:

      var foo = "hey";
      function blarg () {
      var foo;
      somefunc(foo); // still undefined, but no warning
      if (false) {
      foo = "baz";
      // etc

      > The only time I have seen this inaccurately reported is in regard
      > to immediate invocation of a function declared as a variable the
      > same time it is being declared. Example:
      > var a, b,
      > c = (function () {
      > do or report something automatically
      > }());
      > In that example JSLint would report var c as unused, which is not
      > accurate.

      Unless you use c inside the (function)(), or further down in the
      current scope, it definitely will be unused. What's the problem?

      People, please read the specs, instead of just speculating.

      - Conrad
    • Show all 25 messages in this topic