2018-10-12 15:37:13 -04:00
---
title: Prevent Infinite Loops with a Valid Terminal Condition
---
2019-07-24 00:59:27 -07:00
# Prevent Infinite Loops with a Valid Terminal Condition
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Problem Explanation
2018-10-12 15:37:13 -04:00
- To prevent an infinite loop, the `while-condition` must reach a terminal condition to exit out of the loop.
- So the error in this challenge occurs due to the condition - `i != 4` - in the for loop.
- If you take a closer look at the code:
2019-07-24 00:59:27 -07:00
2018-10-12 15:37:13 -04:00
```javascript
function myFunc() {
for (let i = 1; i != 4; i += 2) {
console.log("Still going!");
}
}
```
- You will see that `i` is first initialised as 1 and after every iteration of the loop, `i` is incremented by 2.
- Using this logic, after the first iteration - `i = 3` and the second iteration `i = 5` , the condition `i != 4` will never be met and an infinite loop will occur.
2019-07-24 00:59:27 -07:00
---
## Solutions
< details > < summary > Solution 1 (Click to Show/Hide)< / summary >
2018-10-12 15:37:13 -04:00
```javascript
function myFunc() {
for (let i = 1; i < = 4; i += 2) {
console.log("Still going!");
}
}
```
2019-07-24 00:59:27 -07:00
< / details >