r/programming • • Dec 22 '11

The Problem with Implicit Scoping in CoffeeScript

http://lucumr.pocoo.org/2011/12/22/implicit-scoping-in-coffeescript/
83 Upvotes

116 comments sorted by

View all comments

Show parent comment

1

u/chrisdoner Dec 24 '11 edited Dec 24 '11

I don't think it semantically makes a difference for C programmers, nor JavaScript programmers (disregarding closure behaviour). I tried doing a de-sugaring myself1 (and then read more of your message and read a similar de-sugaring in the mailing list thread you linked). After doing so, it seems to me to be, for a programmer not using closures, completely the same. In both cases below I can mutate the variable in the body, and in all the for(…;…;…) clauses. It seems to me the implementation detail doesn't make a difference to the semantics. There are even optimization opportunities; there can be a test: if the var isn't a free-variable in any sub closures, it can therefore be translated to a for-loop. Right?

1:

(I realise this doesn't include break/continue, etc.)

for(var i = 0;i < 10;i++){
 callbacks.push(function(){ print(i); });
 i *= 2;
}

would be semantically equivalent to

var callbacks = [];
var iter = function(i){
  if(i < 10) {
    callbacks.push(function(){ print(i); });
    i *= 2;
    i++;
    iter(i);
  }
}
iter(0);

To avoid, for whatever reason, rebinding, you can still do:

var i = 0;
for(;i < 10;i++){
  callbacks.push(function(){ print(i); });
  i *= 2;
}

would be semantically equivalent to

var i = 0;
var iter = function(){
  if(i < 10){ 
    callbacks.push(function(){ print(i); });
    i *= 2;
    i++;
    iter();
  }
}
iter();

(which could be optimized to a normal iter-less loop.)