How to imitate `let` behavior in loops?
vzakharov opened this issue · 5 comments
Here’s a screenshot demonstrating some sample CS code, its translation to JS, and the log showing the incorrect (for me) behavior, along with the correct one:

The code is:
keys = ['a', 'b', 'c']
func = {}
for key in keys
func[key] = => key
console.log func.a()
console.log func.b()I want a behavior where it logs the key that the function was created with, not the last key assigned (because coffescript seems to be assigning to global variables).
Is there a way to circumvent this?
After reading this, I kind of get why CS doesn’t have let, but my question is more about solving a practical issue rather than syntax.
If, for example, I loop through all the properties of an object and want to create something for each property (say, a watcher), I need to be able to refer to that thing that this something was created for. And currently I don’t really see how this is achievable with CS.
Still keeping it open to get an expert answer on whether my solution is the “ideologically correct” one.
The standard CoffeeScript solution is:
for key in keys
do (key) =>
funcs[key] = => keyI think it'd be great to add the shorthand for let key in keys for this common case, though.
Yes, do is the idiomatic way to create a new scope (like you’re wishing you could have the for loop do, which it does for let/const variables). And since [].forEach takes a callback function, within that callback is a new function scope just like do creates, so that’s also a fine solution and perhaps simpler to understand.
Closing as there has been lots of discussion of let/const elsewhere and I don’t see it getting revisited anytime soon. If we design a way to “opt in” to block-scoped variables, a proposal to do so should get its own thread and also not cause any breaking changes.
