Loops
for loops
only run when the condition is true
When you use a number in a condition, JavaScript understands 1 to mean true and 0 to mean false.
a. A more efficient way to code to increment up by 1 is to write i++.
b. We decrement down by 1 by writing i--.
c. We can increment up by any value by writing i += x, where x is how much we want to increment up by. e.g., i += 3 counts up by 3s.
d. We can decrement down by any value by writing i -= x.
e. Be very careful with your syntax—if you write a loop that can't properly end, it's called an infinite loop. It will crash your browser!
Structure of for loops:
for (var i = start; i < end; i++) {
// do something
}
Example print out numbers starting at 100 till 0 in 5er steps
for (var i = 100; i > 0; i-=5){
console.log(i);
}
for loops with arrays
Put commas between each element in the array.
Put semi-colons between each bit of the for loop.
Use i as the iterator.
Example: Let's print out every element of an array using a for loop:
var cities = ["Melbourne", "Amman", "Helsinki", "NYC", "Berlin", "Amsterdam"];
for (var i = 0; i < cities.length; i++) {
console.log("I would like to visit " + cities[i]);
}
while loops
Use a while loop if you don't know in advance when to stop looping
Structure of while loops:
while(condition) {
// Do something!
}
Always include a way to ensure the condition between the while parentheses can change, otherwise the loop is infinite and the browser will crash
When we give a variable the boolean value true, we check that variable directly—we don't bother with ===.
Example:
var bool = true;
while(bool){
//Do something
}
is the same thing as
var bool = true;
while(bool === true){
//Do something
}
Remember to set up the condition you're checking outside the loop—if you do it in the loop, it will keep resetting and the loop could go on forever!
Examples for while loops programming:
Task: print " I'm looping 3 times"
var count = 0
var loop = function(){
while(count<3){
count ++
console.log("I'm looping!")
}
};
loop()
=> no need to give the function a name!
No semicolons inside the { }