Languages

JavaScript - break for loop with condition

2 points
Asked by:
AnnLen
1879

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 answers
2 points
Answered by:
AnnLen
1879

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
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join