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

525Re: [jslint] Undefined variable

Expand Messages
  • Michael Lorton
    May 27, 2009
      Nagy Endre <forewer2000@...> writes:

      I'm trying to check if a variable is already defined and define if is not.

      If (Testvar === undefined) {
      var Testvar = {};

      JsLint say that Testvar was used before was defined.
      How can I check this in the right way?

      You are confusing "defined" with "set". A variable is "defined" when the language becomes aware of it and its scope (and, in statically typed languages, its type). It's a Bad Part of Javascript that using a previously undefined variable defines it, in the global scope. You should use the "var" keyword instead to avoid ambiguity.

      A variable is "set" when it is assigned a particular value. In Javascript, as in every high-level language I know except Pascal (which uses :=) and Lisp (which uses "setq" et al.), assignment is done by a single equals sign.

      There is never a need to dynamically test if a variable has been defined. You (or JSLint) can just inspect the code statically. As you noticed, a triple-equals compare will tell you if a variable has been set.

      var Testvar; // variable defined but not set
      ... // whole buncha things
      if (Testvar === undefined) // check if it has not been set yet

      [Non-text portions of this message have been removed]
    • Show all 25 messages in this topic