JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a while Loop

Anna Gibson
Anna Gibson
3,365 Points

What's wrong with my loop?

For all intents and purposes it appears my loop is fine can't seem to pick out what the problem is. It keeps saying that it's 'taking too long to load'.

script.js
var count = 0;

while (count <= 26) {
document.write(count);
}

2 Answers

Matt Socha
Matt Socha
6,541 Points

You need to increment count Since count is never increased its always going to be 0, which meets the condition of the loop. Therefore the loop never ends.

add count++ inside the loop

andren
andren
23,746 Points

There are two issues with your loop:

  1. You have created an infinite loop, that is why it's taking too long to load. The loop will run as long as count is less than or equal to 26, and there is nothing in your code that increases the value stored in count, which means it will never change from its initial value of 0.

  2. Your loop will end up running 27 times, not 26. This is because count starts at 0 not at 1.

If you add code to increase count by one each loop, and change the condition to count < 26, which will be 26 times when you start counting from 0. Like this:

var count = 0;

while (count < 26) { // Loop while count is less than 26
    document.write(count);
    count++; // Increase count by 1
}

Then your code will work.