The variable a
used inside the changeValue
function is the global variable a
. This CoffeeScript will be compiled into the following JavaScript:
var a, changeValue; a = 1; changeValue = function() { return a = 3; }; changeValue(); console.log("a: " + a);
To prevent changeValue
from changing the variable a
(i.e., use a local variable), you need to either have a function argument named a
(which would create this function as a local variable) or declare a
as a local variable inside the function using var a = 3;
(not sure what CoffeeScript is for this, I'm not a CoffeeScript guy).
Some examples of the scope of JavaScript variables.
source share