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

527Re: Undefined variable

Expand Messages
  • Douglas Crockford
    May 27, 2009
      --- In jslint_com@yahoogroups.com, Nagy Endre <forewer2000@...> wrote:
      > 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?

      First, you should avoid using global variables.

      Second, replace "If" with "if". JavaScript is case sensitive.

      Third, the var statement should only be used at the top level of a function or compilation unit. It should not be placed in an if because of hoisting and scope issues.

      So assuming that Testvar is a global variable, say

      if (typeof Testvar === 'undefined') {
      Testvar = {};

      Drop the "var".

      I would also add a hint to JSLint that indicates that you intentionally made a global variable and that this isn't a mistake:

      /*global Testvar*/

      Providing such hints allows JSLint to do a better job for you.
    • Show all 25 messages in this topic