Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions in for loop

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
like image 642
Tron Avatar asked Oct 23 '13 15:10

Tron


People also ask

Can you have more than one condition in a for loop?

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.

How many conditions are there when using for loops in JavaScript?

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:

Can you have multiple logical conditions in an IF-statement?

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?

How do you combine multiple conditions in an IF statement?

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.


1 Answers

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.

like image 185
Ry- Avatar answered Oct 08 '22 04:10

Ry-