coffeescript icon indicating copy to clipboard operation
coffeescript copied to clipboard

break and continue causes looping expression to return empty array

Open OnesimusUnbound opened this issue 15 years ago • 5 comments

The CoffeeScript below will return an empty Array due to break statement. The continue statement has the same effect.

# CoffeeScript
a = for item in [1...10]
    if item > 5 then break else item

// generated JavaScript
var a, item;
a = (function() {
  var _results;
  _results = [];
  for (item = 1; item < 10; item++) {
    if (item > 5) {
      break;
    } else {
      item;
    }
  }
  return _results;
})();

However, the return statement used in place of break will throw a better compiler error cannot use a pure statement in an expression. This error should appear for break and continue for my example above.

OnesimusUnbound avatar Mar 23 '11 14:03 OnesimusUnbound

I believe it has to do with how we are treating breaks and continues as literals, while we treat returns specially. So Literal::jumps may be incorrect.

michaelficarra avatar Mar 23 '11 15:03 michaelficarra

This one needs a little more discussion about the use cases and expected semantics of return, break, and continue within comprehensions. Labeling as notice.

michaelficarra avatar Jul 30 '11 02:07 michaelficarra

I return to the issue and it appears that break and continue within the loop expression returns result

a = for item in [1...10]
    if item <= 5 then item else break

console.log a # returns [1, 2, 3, 4, 5]

Using return in place of either break or continue will cause the cannot use a pure statement in an expression. error.

Well, I'm quite fine with how break and continue are implemented in this case.

OnesimusUnbound avatar Mar 07 '13 16:03 OnesimusUnbound

It's because coffee does not optimize this case and generates an IIFE.

vendethiel avatar Mar 07 '13 16:03 vendethiel

I'll be closing this since it appears that the returned array from the said is consistent with the behavior of the loop with if and break or continue in it.

OnesimusUnbound avatar Mar 08 '13 04:03 OnesimusUnbound