Stop a for loop in JavaScript

How to stop a for loop in JavaScript

Posted by Ervin Adams on August 31, 2022

Stop a for loop in JavaScript

How to stop a for loop in JavaScript

Posted by Ervin Adams on August 31, 2022

Here is how you can stop a for loop in JavaScript.

Use the break keyword to stop a loop at a certain point. The break causes the code execution to exit the loop and start at the next statement in the program.

Here is an example below:

let items = ['bread', 'cake', 'eggs', 'orange juice', 'bottle water'];

let result = null;

for (let i = 0; i < items.length; i++) {
  if (items[i] === 'eggs') {
    result = items[i];
    break;
  }
}

console.log(result); // eggs

In the case above, once the condition was true, the loop stopped and the code executon went on to console.log().