Another type of loop!
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.
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
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
Exercise 1
for(var i = 0; i < 16; i+=8){
console.log(i);
}
Exercise 2
var str = "ahceclwlxo";
for(var i = 1; i < str.length; i+=2){
console.log(str[i]);
}