1-8 For Loops

For Loops are used to execute the same code a certain number of times. They are a great way to cut down on the amount of code you need to type.

Syntax

for (initialization; condition; final expression) {
statements to execute
}

An initialization is used to create a variable with a value before the loop starts.

A condition is an expression to check before each loop. If the condition is true, the statements inside the For Loop are executed. If the condition is false, the loop will end and the program will move to the first line of code after the For Loop.

The final expression is used to increment the counter variable created in the initialization.

Example

for (var i = 0; i < 10; i++) {
var enemy = enemyGroup.create(i * 200 + 100, 0, 'enemy');
}

Example Explanation

This code is used to add 10 enemies to a game with a loop. The first thing that happens is the variable i is initialized with a value of 0 (var i = 0).

Next, the condition i < 10 is evaluated. Since i = 0, the condition evaluates to true (since 0 is less than 10). Since the condition evaluated to true, the var enemy = enemyGroup.create(i * 200 + 100, 0, 'enemy'); line of code will execute to create the first enemy.

Before starting the loop over again, you need to increment the variable. i++ will add 1 to the value of i giving it a new value of 1.

This loop will continue to run until the condition i < 10 evaluates to false. This would happen when i has a value of 10. The condition was set at i < 10 since we knew we wanted to create exactly 10 enemies.

We could have added 10 enemies to the game without using a loop in only 10 lines of code, but we accomplished the same thing without as much code. 10 lines of code may not seem like much, but imagine that we want to add 100 enemies. Setting the properties (velocity, bounce, animation) of the enemies would be extra code to do each of those 100 times.

More Information about For Loops

Information about While Loops - these loops execute code while a condition is true