-2

As a condition in for or while loops, can you use a statement without "i"?

For example:

for (let i = 0 ; myArray.length =< 7; i++)

I want the loop to run until my condition is met, but not sure if I can achieve that without including the "i" there.

daskas
  • 9
  • 1

4 Answers4

1

Try

while (myArray.length <= 7) {

}

with <=, not =<

Snow
  • 3,820
  • 3
  • 13
  • 39
1

In this condition you should use while loop

while (condition)
  statement

But you can also use for...of and forEach and same for loop like below:

You can use for...of

const iterable = 'boo';

for (const value of iterable) {
  if(mycondition){
   console.log(value);
  }
}

OR

You can also use forEach

const items = ['item1', 'item2', 'item3']
const copyItems = []
items.forEach(function(item){
  if(mycondition){
   copyItems.push(item)
  }
})

OR

for

for ([initialization]; [condition]; [final-expression])
   statement

for (;;) is an infinite loop equivalent to while (true) because there is no test condition.

for ( ; s < myArray.length ; s++) is a loop with no initialization. s will point to the beginning and is incremented until it end.

Mandeep Singh
  • 1,287
  • 14
  • 34
1

If you have a condition but no need for an iterator, it's customary to use a while loop:

while (myArray.length < 8) {

  [... CODE HERE ...]
}

Further Reading:

Rounin
  • 27,134
  • 9
  • 83
  • 108
  • Thanks! That's actually where I'm studying, however, no examples of loops without an initializer so far. – daskas Apr 17 '21 at 20:58
1
for ( initiaizer; condition; increment) {
    body
}

is the same as:

initializer 
while (condition) {
    body
    increment
}

And you can follow the same rules in each. Meaning initializer and increment are actually optional (for (; false; ) {} is valid). Creating and incrementing a variable called i is just a useful convention and has no special meaning.

For loops were invented to simplify while loops in the common case where you want to basically count from one number to another. If you’re not doing that, a while loop might be better.

Ben West
  • 4,398
  • 1
  • 16
  • 16
  • 2
    `for(;;){ break }` - the condition is optional too, it would just require manually breaking out of the loop. – Emissary Apr 17 '21 at 20:44
  • didn’t realise that, nice! – Ben West Apr 17 '21 at 20:47
  • This is helpful, thanks! No resource I consulted mentioned it or included an example without the i variable. – daskas Apr 17 '21 at 20:49
  • For loops are a bit bizarre and the way they’re structured only really makes sense in reference to while loops (semicolons inside the `()`???). I prefer array methods most of the time. – Ben West Apr 17 '21 at 21:01