thednp
thednp

Reputation: 4479

Javascript: conditional increment or decrement inside for loop properties

I know I can do an IF ELSE, but I need to know if it is possible to set conditional loop, like so:

for ( i=0; i<la; dr?(i++):(i--) ) {}

or

for ( if (dr) { i=0; i<length; i++ } else { i=length-1; i--} ) {}

Upvotes: 4

Views: 4469

Answers (4)

Touffy
Touffy

Reputation: 6561

Another, still compact (moreso, even) but more readable and efficient way to do it would be:

var str = 'hello';
for(var i=(dr?0:str.length-1), d=(dr?1:-1); str[i]; i+=d) do_something();

And if you put 1 or -1 in dr, which makes sense I think:

for(var i=+(dr===-1&&str.length-1); str[i]; i+=dr) do_something();

Upvotes: 3

Mayukh Roy
Mayukh Roy

Reputation: 1815

  1. The first is good and working. for this:

    for ( i=0; i<4; dr?(i++):(i--) )

    Check jsFiddle here

  2. The Second one is NOT ok as for loop expects an identifier and instead got 'if'.

Upvotes: 0

mathieu
mathieu

Reputation: 477

First is ok. (but you probably have to use a?b:c on your end_condition too) Second is: syntax error ^^

Crazy way:

var str = 'hello';
for(i=(dr?0:str.length-1);(dr?i<str.length:i>=0);(dr?i++:i--)) do_something();

Right way:

   var str = 'hello';
   if(dr)
      for(i=0;i<str.length;i++) do_something();
   else
      for(i=str.length-1;i>=0;i--) do_something();

(code not tested)

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

Yes it is fine to use a conditional loop but it is not recommended as it becomes really hard for someone new who tries to understand your code. The code is not readable if you use the first syntax. The second syntax is much readable so I think you should prefer to use it.

But if you are are fine to use the first version of the syntax then go with it. You should always use the code which is easiest to read and maintain.

Upvotes: 0

Related Questions