Stop a for loop from continuing in JavaScript?

Answered
yaboy01 asked this question 21 days ago
yaboy01 21 days ago

I have a JavaScript for loop that looks like this:

for (let i=0; i < array.length; i++) {
  if (array.points < 10) {
    // do something
  } else {
    // stop the for loop here
  }
}

How do I stop the for loop from continuing in the example code I provided above?

2 suggested answers
nick 13 days ago

Use the break statement:

break

It jumps out of the loop and stops any additional iterations.

0 replies
suparman21 13 days ago

The break statement will do the trick for you.

Update your code to the following:

for (let i=0; i < array.length; i++) {
  if (array.points < 10) {
    // do something
  } else {
   break
  }
}
0 replies
Answered