For Loops

Another type of loop!

Objectives

  • Understand the purpose of for loops
  • Write valid for loops
  • Compare and contrast while loops and for loops

For Loops

Another way of repeating code

for(init; condition; step) {
  //run some code
}

It looks weird, I know.  Let's take a look at an example.

For Loops

Printing numbers from 1-5 with a for loop

for(var count = 0; count < 6; count++) {
  console.log(count);
}
var count = 1;

while(count < 6) {
 console.log("count is: " + count);
 count++;
}

Printing numbers from 1-5 with a while loop

For Loops

Printing each character in a string with a for loop

var str = "hello";
var count = 0;   
 
while(count < str.length) {
 console.log(str[count]);
 count++;
}
var str = "hello";

for(var i = 0; i < str.length; i++){
  console.log(str[i]);
}

And with a while loop

For Loops

Exercise 1

for(var i = 0; i < 16; i+=8){
  console.log(i);
}

For Loops

Exercise 2

var str = "ahceclwlxo";

for(var i = 1; i < str.length; i+=2){
  console.log(str[i]);
}

Printer Friendly - For Loops

By Colt Steele

Printer Friendly - For Loops

  • 2,263