TheBrent
TheBrent

Reputation: 2863

Usage of compound conditional statements within JavaScript for loop

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++) {};

Upvotes: 0

Views: 1143

Answers (2)

Esailija
Esailija

Reputation: 140210

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.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 59997

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.

Upvotes: 0

Related Questions