Prevent Endless Loops in JavaScript ꔛ
Tags: javascript, programming, todayilearned, webdev
Published: 2022-05-23 09:40:33

I accidentally created an endless loop in JavaScript that made my browser crash. How is this even possible in 2022?

Consider the following code:

```javascript
const mightBeZero = 0;
const maxIterations = 100 / mightBeZero;
console.log(`maxIterations: ${maxIterations}`);

for (let i = 0; i < maxIterations; i++) {
  // do costly stuff like appending cloned DOM nodes
}
```

While at least [CodePen](https://codepen.io/openmindculture/pen/GRyyEBX) seems smart enough to protect their users, ESLint seems to have nothing to criticize except that I used `++` instead of `+= 1`.
![Screenshot of infinity loop code in Codepen and PhpStorm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sex0pzcpiwtvbtl1a9zn.png)

Despite the endless loop, why does division by zero equals `Infinity` in JavaScript while many other programming languages throw a `DivisionByZero` exception?

{% post https://dev.to/mtrivera/divide-by-zero-equals-infinity-3pmd %}

And why did we fail to [handle JavaScript's division by zero properly](https://stackoverflow.com/questions/8072323/best-way-to-prevent-handle-divide-by-0-in-javascript) in our code?

## Failure Chain

1. My quick and dirty, naive, happy-path code failed to envision edge cases (using `offsetWidth` without checking for 0 width of a hidden `width: auto` element)
2. JavaScript failed to throw a Division by Zero exception but calculating `x / 0 = Infinity` instead
3. JavaScript not refusing to do a loop `for (let i=0; i < Infinity; i += 1)
4. eslint failed to warn (after "fixing" `i++` to `i += 1` everything seemed to be fine?!)
5. PhpStorm code inspection, quite smart even for JavaScript otherwise, did not warn either.
6. A coworker approved and merged my code.
7. Another coworker added the case that triggers the zero / infinity bug.
8. My browser ([Chromium](https://www.chromium.org/)-based [Vivaldi](https://vivaldi.com/)) did not offer to stop the loop like Firefox used to do (TODO check if Firefox still does). (There is a task manager in the developer tools with an option to stop though.)
9. The browser keeps reopening the same tab and executing the same cached front-end code after I stopped my preview server and also after I restarted the server with a code fix!

## Solutions and follow-up Issues

- Code more intelligently!
Not bad, but that's never guaranteed to prevent errors like that, as [to err is human](https://idioms.thefreedictionary.com/to+err+is+human) and it takes more than will power to increase intelligence.

- Write tests and test the tests! There are meta strategies like [mutation testing](https://en.wikipedia.org/wiki/Mutation_testing). The challenge is not the testing itself, it's to learn how to architect your code so that it is testable.

- What about tooling and static code analysis? This one wouldn't upset me that much if the linters didn't complain about anything. But often those "artficially intelligent" tools act even more unhelpfully by nagging about the wrong things (see my [rant about linting the wrong code](https://dev.to/ingosteinke/i-enjoy-life-long-learning-but--5efh#linting-the-wrong-code) that I posted on the DEV blog last year).

- What about browser safety? Crashing my browser with my own infinite loop on localhost is half as bad, but what if this was part of a malicious hacker scheme targeting customers in production? How to kill a distinct browser tab or stop a JavaScript process as a regular user with no knowledge about developer tools?

## Resolutions

- learn to code better
- do more testing (unit testing my JavaScript functions, end-to-end testing web applications, testing the tests)
- open an eslint issue unless there already is one
- open a Chromium issue unless there already is one
- write about it on DEV.to :heavy_check_mark: