EN
JavaScript - break for loop with condition
1 answers
2 points
How can I break the for loop in JavaScript when the iteration i variable is equal to some value?
Code example:
xxxxxxxxxx
1
for (var i = 0; i < 7; i++) {
2
console.log("i: " + i);
3
}
Output:
xxxxxxxxxx
1
i: 0
2
i: 1
3
i: 2
4
i: 3
5
i: 4
6
i: 5
7
i: 6
How to cancel iteration of this for loop when i is equal to 3?
1 answer
2 points
Quick solution:
xxxxxxxxxx
1
for (var i = 0; i < 7; i++) {
2
if (i == 3) {
3
break;
4
}
5
console.log("i: " + i);
6
}
Output:
xxxxxxxxxx
1
i: 0
2
i: 1
3
i: 2
We just need to use if with break keyword.
Explanation:
The break keyword statement jumps out of a for loop.
0 commentsShow commentsAdd comment