How to force a variable to be local in coffeescript?
coffeescript
Solution
This kind of error usually comes up when you aren't using appropriately descriptive variable names. That said, there is a way to shadow an outer variable, despite what the accepted answer says:
outer=1
f=->
do (outer) ->
local=1
outer=0
local+outer
This creates an IIFE, with `outer` as it's one argument. Function arguments shadow outer variables just like the `var` keyword, so this will have the behavior you expect. However, like I said, you should really just name your variables more descriptively.
Problem
Given the following code: ``` outer=1 f=-> local=1 outer=0 local+outer ``` coffeescript creates a `var` for `local` but re-ueses `outer`: ``` var f, outer; outer = 1; f = function() { var local; local = 1; outer = 0; return local + outer; }; ``` Which is what your expect. However, if you use a local variable in a function it depends on the outer scope if the variable is declared local or not. I know this is a feature, but it was causing some bugs, because I have to check all outer scopes for variables with the same name (which are declared before my function). I wonder if there is a way to prevent this type of bug by declaring variables local?