0

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

6
  • Visit this link w3schools.com/js/js_loop_for.asp Commented Apr 3, 2015 at 12:50
  • @choxx I know how FOR works, I was just wondering if it's possible to do it in the way I asked. Commented Apr 3, 2015 at 12:53
  • GUYS, the question wasnt about how a for loop works.. please keep in mind when downvoting. Commented Apr 3, 2015 at 12:54
  • Well then you must also know the code you wrote in Ist part doesn't make any sense.. Commented Apr 3, 2015 at 13:56
  • You can't directly write i < x.length || 10; If you are assigning multiple conditions in FOR, then you must have to follow the coding rules as per standard. i < x.length || i < 10; Commented Apr 3, 2015 at 13:58

2 Answers 2

5

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++) {
Sign up to request clarification or add additional context in comments.

7 Comments

isn't it possible in the simple way as I wrote it? like i < x.length || 10;
@KissKoppány no, this writing makes no sense
No it isnt possible this way
@MoisheLipsker No, you'd need to use &&. Otherwise, if x.length is smaller than 10 you'll go out of bounds.
@dystroy your solution is nice and kind of what I was looking for: for (var i=0; i<Math.min(x.length,10); i++) { Nice and clear.
|
2

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.

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.