How can I write a for loop with multiple conditions?
Intended Javascript:
for(k=1; k < 120 && myThing.someValue > 1234; k++){
myThing
Since a for
loop is equivalent to a while
loop plus a couple of statements, and CoffeeScript offers only one kind of for
loop, use a while
loop. If you’re trying to get specific JavaScript output, you should probably not be using CoffeeScript.
Of course, there is always
`for(k=1; k < 120 && myThing.someValue > 1234; k++) {`
do myThing.action
`}`
Avoid.
Trying to write CoffeeScript that produces specific JavaScript is a bit silly and pointless so don't do that.
Instead, translate the code's intent to CoffeeScript. You could say:
for k in [1...120]
break if(myThing.someValue <= 1234)
myThing.action()
And if you're not actually using the loop index for anything, leave it out:
for [1...120]
break if(myThing.someValue <= 1234)
myThing.action()
Both of those produce JavaScript that is structured like this:
for(k = 1; k < 120; k++) {
if(myThing.someValue <= 1234)
break;
myThing.action();
}
That should have the same effect as your loop. Furthermore, I tend to think that those three loops are more maintainable than your original as they don't hide the exceptional condition inside the loop condition, they put it right in your face so you can't miss it; this is, of course, just my opinion.