# How To Stop A For Loop In JavaScript

In this article, you’ll learn how to stop a for loop in JavaScript by understanding how the loop works and or use the break keyword. Let’s go into detail now!

## Stop a For Loop in JavaScript

### Understanding the for loop

A loop is a way to repeat a certain action (i.e. executes a piece of code) multiple times depending on a condition.

In this article we’ll be talking about the for loop: A for loop is a loop with three expression parameters – the initialization, condition and afterthought and executes the code encapsulated in curly brackets ({}).

Syntax:

for(initialization, condition, afterthought) {}

Parameters:

• initialization: An expression that declares a variable (using either the let or var keyword) before the loop begins and gets disposed/deleted after the loop ends. Note that the variable’s value will be changed, so you cannot use the const keyword to initialize the variable.
• condition: Will be checked before every iteration; if the condition returns true the loop’s code will be executed; if false the loop will end.
• afterthought: An expression that is executed after every iteration but before every condition check.

So, considering it, we have the timeline of events:

1. A variable is declared by the initialization variable.
2. A condition is checked; if it returns true continue to step 3; if not end the loop.
3. Execute the loop’s code.
4. Execute the afterthought parameter’s statement/code.

### Guaranteeing the Condition Parameter is False

As mentioned above, the loop will be terminated if the condition parameter’s statement returns false. So a way to stop a loop is to guarantee the condition is false.

For example, we have something like this:

Code:

const arr = ["a", "LearnShareIT", "end", "14514", "123"];

for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
if (arr[i] === "end") i = arr.length;
}

Output:

a
LearnShareIT
end

As we can see, the loop ended when the iterated value from the array equated to "end" which immediately set i to the length of the array (i.e. the condition now returns false).

However, this may be a little inconvenient as you need to manually guarantee the false condition, while you can use an interrupt statement instead.

### Using the break Statement

As the name implies, the break statement breaks a loop (while loops, for loops, etc.). So a revised version of the code would be something like this:

Code:

const arr = ["a", "LearnShareIT", "end", "14514", "123"];

for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
if (arr[i] === "end") break;
}

Output:

a
LearnShareIT
end

## Summary

To stop a for loop in JavaScript, you need to make sure the condition parameter is set in the loop that returns false or use the break keyword. Let’s try these methods!

Maybe you are interested: