Languages

JavaScript - break for loop with condition

2 points
Asked by:
AnnLen
12070

How can I break the for loop in JavaScript when the iteration i variable is equal to some value?

Code example:

// ONLINE-RUNNER:browser;

for (var i = 0; i < 7; i++) {
    console.log("i: " + i);
}

Output:

i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6

How to cancel iteration of this for loop when i is equal to 3?

1 answer
2 points
Answered by:
AnnLen
12070

Quick solution:

// ONLINE-RUNNER:browser;

for (var i = 0; i < 7; i++) {
    if (i == 3) {
        break;
    }
    console.log("i: " + i);
}

Output:

i: 0
i: 1
i: 2

We just need to use if with break keyword.

Explanation:

The break keyword statement jumps out of a for loop.

0 comments Add comment
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join