The LOOP

The loop is a fantastic tool for any function that involves doing the same thing more than once. If I wanted to write my name 10 times, I would write a loop like this:

START LOOP (REPEAT 10 TIMES)
    Write my Name
END OF LOOP

Of course that's not how I would type it. To create a loop I need to use the FOR statement. It is written like this:

for (count = 1; count <= 10; count++) {
    (stuff I want to do 10 times)
}

This statement would be read outloud:

"For count equals one, while count is less than or equal to ten, incrementing by one"

The FOR statement above will begin by creating a variable called count (you can choose any variable name). Initially, count will equal 1. The computer will perform whatever commands are between the curly brackets, then upon reaching the end of the loop, count is incremented by 1, and a question is asked:

IS COUNT LESS THAN OR EQUAL TO 10?

If the answer is YES, then the loop repeats. If the answer is no, then the program exits the loop, and goes on with the program.


Here is a function designed to display an alert box with the number 1 in it, then with the number 2, then with a 3, then a 4, then a 5, and then stop.

for (count = 1; count <= 5; count++) {
    alert(count)
}


results matching ""

    No results matching ""