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

Re: 'variable' was used before it was defined

Expand Messages
  • demirozba
    Thank you very much, this answer is really helpful
    Message 1 of 6 , Feb 11, 2010
    • 0 Attachment
      Thank you very much, this answer is really helpful

      --- In jslint_com@yahoogroups.com, "Aseem" <aseem.kishore@...> wrote:
      >
      > Actually, if you're using this pattern to check if a user-specified option is set or not, explicitly using "var" is not the way to go.
      >
      > In IE, at a script level (i.e. per file, or per script block), if it sees a "var" declaration during its parse phase (before execution), it will reset the value of that variable if it already existed.
      >
      > So better would be to simply do this:
      >
      > /*global foo: true */
      > if (typeof foo === "undefined") {
      > foo = "some value";
      > }
      >
      > By not declaring "var" and simply assigning foo, foo will automatically get global scope.
      >
      > You can tell JSLint that foo may be defined by putting it in the /*global */ declaration; that will prevent the "used before it was defined" error for the line where you check if foo is undefined. By saying "foo: true" in that declaration, you tell JSLint that you're also planning to modify that global variable, so then there's no error on the assignment line.
      >
      > Unrelated, but note the use of === instead of == and the lack of parentheses after "typeof". Both are best practices recommended by JSLint.
      >
      > Cheers,
      > Aseem
      >
      > --- In jslint_com@yahoogroups.com, "Douglas Crockford" <douglas@> wrote:
      > >
      > > --- In jslint_com@yahoogroups.com, "demirozba" <baris@> wrote:
      > > >
      > > > I am checking if a variable is defined or not, if it is not defined explicitly I am going to define it by doing:
      > > >
      > > > if ( typeof(aVariable) == 'undefined' ) {
      > > > var aVariable = value;
      > > > }
      > > >
      > > > Because the variable is not defined I get the JSLint advice that it is used before it was not defined, and that is exactly what I want.
      > > >
      > > > What is the best practice to overcome this?
      > >
      > > var aVariable;
      > >
      > > if (aVariable === undefined) {
      > > aVariable = value;
      > > }
      > >
      >
    Your message has been successfully submitted and would be delivered to recipients shortly.