Question

For the following code:

inc = -> value = (value ? 0) + 1
dec = -> value = (value ? 0) - 1
print = -> console.log value ? 0

How can you make this work properly, so inc and dec close upon value instead of creating separate function-local variables, in the way other than explicitly assigning something to value?

In plain Javascript, you would just declare var value at outer scope:

var value;

function inc() { value = (value || 0) + 1; };
function dec() { value = (value || 0) - 1; };
function print() { console.log(value || 0); };

What is CoffeeScript way for exactly the same thing?

Was it helpful?

Solution

In CoffeeScript, the way to introduce a local variable is to assign to the variable in the appropriate scope.

This is simply the way that CoffeeScript was defined and as such is similar to Python or Ruby, which do not require a "variable declaration", except CoffeeScript also allows forward access. A side-effect is that one cannot shadow a lexical variable.

Just as with the placement of var in JavaScript, where this assignment is done (as long as it is in the correct scope) does not affect the scope of the variable.

Given

x = undefined
f = -> x
// JS
var f, x;
x = void 0;
f = function() {
  return x;
};

Given

f = -> x
x = undefined
// JS
var f, x;
f = function() {
  return x;
};
x = void 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top