How do I build a loop in JavaScript? [closed]

For loops

for (i = startValue; i <= endValue; i++) {
    // Before the loop: i is set to startValue
    // After each iteration of the loop: i++ is executed
    // The loop continues as long as i <= endValue is true
}

For…in loops

for (i in things) {
    // If things is an array, i will usually contain the array keys *not advised*
    // If things is an object, i will contain the member names
    // Either way, access values using: things[i]
}

It is bad practice to use for...in loops to itterate over arrays. It goes against the ECMA 262 standard and can cause problems when non-standard attributes or methods are added to the Array object, e.g. by Prototype.
(Thanks to Chase Seibert for pointing this out in the comments)

While loops

while (myCondition) {
    // The loop will continue until myCondition is false
}

Leave a Comment