Kiss Koppány
Kiss Koppány

Reputation: 950

Complex condition in FOR loop in JavaScript

I was wondering if it's possible to state 2 statements as a FOR loop's condition in JavaScript.

for (var i = 0; i < x.length || 10; i++) {

}

instead of writing

for (var i = 0; i < x.length; i++) {
    if(i<10) {

    }
}

Used references (didn't help too much):

Multiple conditions in for loop

Multiple conditions in for statement

Upvotes: 0

Views: 2454

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

If the goal is to end the loop when i reaches 10 or i reaches the end of the array, you may write it like this :

for (var i=0; i<x.length && i<10; i++) {

In that case you might also compose it like this

for (var i=0; i<Math.min(x.length,10); i++) {

or for better performances :

for (var i=0, n=Math.min(x.length,10); i<n; i++) {

Upvotes: 5

Paolo
Paolo

Reputation: 15827

The problem is not in the syntax of the for loop but in the way you put the conditional stetement:

i < x.length || 10

evaluates as

(i < x.length) || 10

that evaluates as

true || 10

or

false || 10

depending on the value of i and the length of x

The first will then result in true while the latter in 10.

So the for loop goes on forever and is not equivalent to the second code snipped you posted.

The above is to explain why the two code snippets you posted are not functionally equivalent.

The correct statement is

for (var i=0; i<x.length && i<10; i++) {

or one of the other proposed in dystroy's excellent answer.

Upvotes: 2

Related Questions