Infinite loops are an essential tool in web development. They allow developers to write the same piece of code over and over without the need to repeat the code manually. The said code will also often have slight differences within every single iteration.
For instance, you need to create a table with 100 columns. Each column should have two rows, the first row being the header, which should have a number corresponding to the said column, starting from one. Here is what your code would look like without loops:
{% code-block language="js" %}
<table>
<tr>
<th>1</th>
<th>2</th>
// repeats 96 times
<th>99</th>
<th>100</th>
</tr>
<tr>
<td>Some text</td>
<td>Some text</td>
// repeats 96 times
<td>Some text</td>
<td>Some text</td>
</tr>
</table>
{% code-block-end %}
Whereas using loops, your code would look like this:
{% code-block language="js" %} <script>
function tableCreate() {
const body = document.body,
tbl = document.createElement("table");
for (let i = 0; i < 2; i++) {
const tr = tbl.insertRow();
for (let j = 1; j < 100; j++) {
const th = tr.insertCell();
if (i == 0) {
th.appendChild(document.createTextNode(`${j}`));
} else {
th.appendChild(document.createTextNode(`some text`));
}
}
}
body.appendChild(tbl);
};
tableCreate();
</script>
{% code-block-end %}
It might look a bit more complex. But not only have we turned more than 200 lines of code in less than 20, but we also kept our code DRY (aka non-repetitive).
An infinite loop is a condition that happens whenever faulty logic prevents the loop/iteration from ending.
Suppose that in the example above, I forgot the increment expression (I will go through it later in this article) in the first loop. That would cause the browser to infinitely create a table header with the number one.
If you run the defect loop locally, it can make the whole environment crash or even make your computer stop responding. The same could happen if you pushed a failing loop into a web page. For instance, it could crash the page, return a white screen, or even freeze the browser.
Before diving into how to avoid an infinite loop, I’ll give you an overview of the most used loops supported in Javascript.
I’ll be giving examples; in all loops the expected outcome is to have an array like this:
{% code-block language="js" %}
[0, 1, 2, 3, 4, 5]
{% code-block-end %}
The for loop repeats until the condition becomes false.
{% code-block language="js" %}
for ([initialExpression]; [conditionExpression]; [incrementExpression])
statement
{% code-block-end %}
The initialExpression it’s used to initialize the loop, usually by declaring some variable. After that, the conditionExpression is called. If it remains true, the loop continues. If the value is false, it stops.
The statement is then executed, and the increment expression runs—the loop restarts from the conditionExpression.
for loop example
{% code-block language="js" %}
let array= [];
for (let i = 0; i < 6; i++) {
array.push(i);
console.log(array);
}
{% code-block-end %}
The do…while loop repeats while the condition is true.
{% code-block language="js" %} do
statement
while (conditionExpression);
{% code-block-end %}
The statement will run once before evaluating the condition. If it’s true, it executes again. If it’s false, it stops.
{% code-block language="js" %} let array= [];
let i = 0;
do {
array.push(i);
console.log(array);
i++;
} while (i < 6);
{% code-block-end %}
The while loop repeats while the condition is true.
{% code-block language="js" %}
while (conditionExpression)
statement
{% code-block-end %}
Unlike the do…while loop, the statement runs only after the condition is evaluated.
{% code-block language="js" %} let array= [];
let i = 0;
while (i < 6) {
array.push(i);
console.log(array);
i++;
}; {% code-block-end %}
Now that we’ve gone through the most common loops let’s dive into how to avoid infinite iterations on them. In this section, I’ll present things to remember when writing loops and examples of infinite loops.
IMPORTANT! Keep in mind that if you want to try any of the following loops, it should be done in a console that can be easily terminated. Trying to run these in your browser console can cause a browser crash or even freeze your computer.
The first and simplest way to write an infinite for loop, is to omit all three expressions:
{% code-block language="js" %}
for (;;) { //do something }
{% code-block-end %}
But if you want to prevent infinite for loops from happening, keep the following in mind:
For item one, suppose you have the same loop as the given example, but instead of increasing by one, you decrease by one. This means that you will have an ever-growing array of negative numbers, so the
{% code-block language="js" %}
i< 6
{% code-block-end %}
condition will always be true.
To prevent this from happening to for loops that use increment, your condition should always be larger than the initial expression. For decrements, it’s the other way around. You could use the following loops as a base to write your code:
{% code-block language="js" %}
\
// to iterate 5 times forward:
for (let i = 0; i < 6; i++) { ... }
// to iterate 5 times backward:
for (let i = 5; i >= 0; i--) { ... }
{% code-block-end %}
Remember that in Javascript, “=” is an assignment operator, not a comparison expression. This means that if a condition such as
{% code-block language="js" %}
i = 6
{% code-block-end %}
it will always be true and, therefore, will result in an infinite loop.
Or, if the loop is:
{% code-block language="js" %}
for (let i = 0; i === 6; i++;)
{ //do something }
{% code-block-end %}
the condition will be false from the very first iteration.This means that the statement wouldn’t run at all, returning undefined.
Item two is self-explanatory. If the initial value of your loop does not increase or decrease, it will never meet the condition.
The main difference between do…while and while loops is whether the statement will run before or after the condition expression is evaluated. Now, I will cover how to avoid infinite loops on both at once.
The first item is straightforward. So always double-check if you have a condition that can eventually be evaluated as false.
Consider the following:
{% code-block language="js" %}\
let i = 0;
while (i < 6) {
// do something
};
{% code-block-end %}
Even though your condition could be evaluated as false at some point, this will loop indefinitely because your variable is not mutating. To fix this, simply add an increment at the end of the statement to ensure that your variable is increasing within every iteration.
{% code-block language="js" %}\
let i = 0;
while (i < 6) {
// do something
i++;
};
{% code-block-end %}
Loops are an essential and powerful tool every developer should master. Not only does it avoid repetition, keeping the code DRY (i.e., non-repetitive), but it can also save hours of writing meaningless code.
But, “With great power comes great responsibility.” Faulty logic can turn loops into a deadly, silent weapon with the power to shut down local environments or completely freeze a computer.
Learn this and many more fundamental tools to boost your web development career. Apply to Microverse today and join more than a thousand Micronauts breaking into international web development roles!
Career advice, the latest coding trends and languages, and insights on how to land a remote job in tech, straight to your inbox.