Top community members

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

JavaScript - break for loop with condition

2 points
Asked by:
AnnLen
1666

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
1666

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

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more