How can I write a for loop with multiple conditions?
Intended Javascript:
for(k=1; k < 120 && myThing.someValue > 1234; k++){
myThing.action();
}
js2coffee.org indicates that I should use a while loop:
k = 1
while k < 120 and myThing.someValue > 1234
myThing.action()
k++
but this ends up compiling back to a while loop in javascript.
Is there a way to write coffescript to compile to my intended javascript and include extra conditions in the for loop itself?
If the answer to that question is false, then what would be the nicest way to get the same functionality with coffeescript?
My best while loop solution so far is
k = 1
myThing.action() while k++ < 120 and myThing.someValue > 1234
I have been programming for years and never until today seen more than one condition in a for loop. I understand it's perfectly valid code, as the && simply gets evaluated and a result returned, I had simply never thought of using multiple conditions inside the for statement instead of the body.
Usually when using for loops in Javascript, there is only ever a need for a single condition, say you want the loop to run 5 times starting from 1, you might use the following code:
However, we may also specify multiple logical conditions within a single if-statement: The output is the same. Note that we could apply the same logic within other types of loops such as repeat-loops or while-loops. Would you like to know more about loops?
You can combine multiple conditions using & (and) and | (or) (&& and || are also things). Using this method I think it's worth combining the first two levels of your if statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With