Also as in Python, we can have definite loops (for loops) and indefinite loops (while loops), but they operate a bit differently.
for (statement 1; statement 2; statement 3) {
code to be executed
}
statement1 is before the loop starts, statement 2 defines how the loop runs, and statement 3 gets executed each time after the loop has run.
var num = 0;
for (var i = 0; i < 5; i = i+1) {
var num = num + i;
}
A variation on this is the for/in loop, which allows you to work your way through an object:
var location = {city: "Centennial"; state: "Colorado"; country: "USA"};
var text = "";
var t;
for (t in location) {
text = text + location[t] + ", ";
}
A while loop is indefinite, it executes until a certain condition becomes false.
var num = 0;
var i = 0;
while (i < 10) {
num = num + i;
i = i + 1;
}
A variation on this is the do/while loop, which executes the loop once, then checks:
var num = 0;
var i = 0;
do {
num = num + i;
i = i + 1;
}
while (i < 10);