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

In this example we will look at how to stop a for loop execution in Javacript.

If you are reading this, you should know that a for loop is used to repeat the execution of a block of code.

For example, if you want to display a list of items from an array, then you can use a for loop

The loop will run through all the items in the list before stop executing. 

However, in some instances you might want stop the execution before the end of the list.

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, the for loop iterates over the list by using the index position; which are numeric values starting from 0.

At each index position there is a string value. In the example above the if condition is looking for a specific string value "egg". 

Once the condition was true, the loop stopped and the code executon went on to console.log().

The console.log() output the value of the item at the index position where the for loop stop executing. However, you can execute whatever script you desire at this junction.

Here is another example:

let numbers = [1, 2, 3, 4, 5, 6];

let result = null;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] > 4) {
    result = numbers[i];
    break;
  }
}

console.log(result); // 5

In the example above, this time the items are numeric. The for loop stop execution when the numeric value is greater than 4.

Now you have an idea of how to break a for loop earlier in its execution.

Any question?
This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question