0

Can you use a compound conditional statement in a JavaScript for loop?

Here is an example,

//using a compound conditional statement
//within a for loop, JavaScript
for (var i=0; i < res.length && i < 5; i++) {};

//or
for (var i=0; i < res.length || i < 5; i++) {};
4
  • Is the fact that your second example might run infinitely an example of such a logic error or just serendipitous irony? Commented Jun 3, 2012 at 22:55
  • It's a logic statement like any other; any errors will be PEBKAC. Commented Jun 3, 2012 at 22:56
  • Serendipitous irony for sure! :) Commented Jun 3, 2012 at 22:56
  • @Niko—I think you mean "yes", the question has been edited. Commented Jun 4, 2012 at 2:51

2 Answers 2

1

Yes it could lead to a logic error -- like any other code. Hopefully you test your code so you can find those errors and fix them.

Sign up to request clarification or add additional context in comments.

Comments

0

Brent - The two statements are not the same. You are trying to use De Morgan's laws. hence the second statement should read

for (var i=0; i >= res.length || i >= 5; i++) {};

It would be better to do this

var end = res.length < 5 ? res.length : 5;

for (var i=0; i < end; ++i) {}

This will reduce the overhead or doing the logic of working out when to terminate the loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.