4.2 - For Loops

Review

  • The while loop works on a condition (or multiple conditions)

while ((x <= 5) && (paused == false)) {
// do something
}


  • A lot of the time, it involves a counting variable - doing the loop a certain number of times

while (count < 100) {
// do something
}


  • Most of the time, we forget to increase/decrease the counting variable, causing an infinite loop!

Today's Lesson: 4.2 - The for Loop

If you know that you need to loop a specific number of times, there is a loop construct specifically for this occasion.

for (let index = 0; index < 10; index++) {

console.log(index);

}

The above code will print the numbers 0 to 9.

You can increment / decrement by whatever amount you need!

for (let i = 100; i > 0; i--) {

// Count down from 100 to 1

}


for (let j = 10; j <= 30; j += 2) {

// Count up by 2's from 10 to 30

}


for (let x = 93; x > 51; x -= 5) {

// Count down by 5's from 93 to 51

}


Slides for this lesson (nothing special)

Interactive Demo for this lesson (once published)

4.2 Task(s) / Homework