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

Re: Bugs with JSLint and global variables.

Expand Messages
  • pauanyu
    ... I gave some more thought to this. Right now, if you want to use the global name and local name , JSLint says you *must* put either var name; or
    Message 1 of 13 , Jun 20, 2009
    • 0 Attachment
      --- In jslint_com@yahoogroups.com, "pauanyu" <pcxunlimited@...> wrote:
      >
      > As an addendum to this, it has been recently decided that "name" is a non-writable global by default, with the intent to catch accidental globals.
      >
      > I offer the solution of using "window.name" when you wish to use the global variable, and "name" when you wish to use the local variable. This is rather trickier with the restriction against "window".
      >
      > This has the benefit of making it extremely obvious to everybody whether you are intending to use the global or local. This improves code readability, and helps to catch errors. We should make the distinction between globals and locals more obvious, not less.
      >

      I gave some more thought to this. Right now, if you want to use the global "name" and local "name", JSLint says you *must* put either "var name;" or /*global name:true */ at the top of your code.

      Why is this bad? Because JSLint now no longer checks if you accidentally leave off a var statement when you intended to use the local "name". It fails silently, causing errors. This is a serious mistake.

      As pointed out, we need to make the distinction between globals and locals more obvious, not less. When both global and local are referred to by the same name, you have a hard time telling them apart, which causes confusion.

      However, we don't want to just allow "window" again. After all, we banned it for a reason, right? Here is my solution.


      You can freely use "window" to refer to *already-declared* global variables:

      // These are okay:
      window.name = 1;
      window.onload = function () {};
      window.addEventListener();


      However! You cannot use "window" to create *new* global variables:

      // This fails with the error "Use var to declare new globals":
      window.foo = function () {};


      Now, you can use "window.name" for global, and "name" for local. If somebody else reads your code, it is now extremely obvious whether you intended the global or local. This reduces confusion and increases maintainability. In addition, if you forget to use "var" to declare the local "name", JSLint will now give you an error! Before, it failed silently.

      Lastly, because you cannot create new globals with "window", this removes the original problem (why we banned it in the first place). The ideal solution.

      P.S. I chose to pick on "name" here, but it could easily be another global, like "top" or "status".
    Your message has been successfully submitted and would be delivered to recipients shortly.