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

Re: [jslint] Scope confusion.

Expand Messages
  • Arthur Blake
    I wonder why the language designers didn t add block scope in the first place.... It would have been a handy feature (it s quite handy in Java) and I can t
    Message 1 of 2 , Aug 28 5:38 PM
    • 0 Attachment
      I wonder why the language designers didn't add block scope in the
      first place....
      It would have been a handy feature (it's quite handy in Java) and I
      can't think of any real downside to having it.

      On Fri, Aug 28, 2009 at 5:55 PM, douglascrockford<douglas@...> wrote:
      >
      >
      > One of the hazards of JavaScript is that its syntax suggests that it has
      > block scope, but it doesn't. It only has function scope. It turns out that
      > function scope is adequate, but if you program assuming block scope, you can
      > be trapped.
      >
      > So JSLint tolerates programs that are written assuming block scope so long
      > as the program can also be read correctly with only function scope.
      >
      > Consider this program:
      >
      > function f() {
      > var x = 1;
      > return function () {
      > if (true) {
      > var x = 2;
      > }
      > return x;
      > };
      > }
      >
      > What is the value of f()()? If you are expecting that there is block scope,
      > then you would expect the result to be 1. But there is no block scope, so
      > the value of f()() is 2.
      >
      > JSLint will complain about the line containing return x; because the inner
      > function shows scope confusion. There is not an interpretation that is
      > consistent with both block scope and function scope, so JSLint gives a
      > warning.
      >
      > Generally, the best option is to use a single var statement at the top of
      > each function. That always reads correctly and always avoids scope
      > confusion.
      >
      >
    Your message has been successfully submitted and would be delivered to recipients shortly.