Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

There are more scopes than that: free variables versus locals; eval-introduced bindings; "with"; the exception identifier in "catch"; the function name in named function expressions; argument names; etc.

And the scoping rules are quite tricky in practice, to real programmers. To take an example from today:

https://bugs.webkit.org/show_bug.cgi?id=27226#c4



Looking at that example, I would ask ....where exactly is that function definition getting defined? Why would you put a function definition inside a catch block? Do you think it's getting defined when the catch block is called? Are you programming in Javascript, or are you just writing javascript the way you would write code in some other language?


It's a pretty straightforward use-case: you have a function that returns a function, and in the case of an internal error, you want the returned function to have a reference to the error object. And the only reliable way to do that is to declare a variable with function scope, declare a function in function scope, and conditionally return this function? That's absurdly broken.

As for variable scoping rules, if you have never been bitten by loop counters being used improperly, then I assert that you haven't programmed enough javascript. There are so many ways to mess this up: forget a var declaration and it leaks scope -- and since you can only declare it once, you can't just always use "for (var i = ...". If you want to defer access to a loop counter, then you have to remember to explicitly pass it by value to an inner closure. That last one in particular bites me all the time -- JSLint at least warns you about the first one.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: