How can I build a loop in JavaScript?
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
}
Here is an example of a for loop:
We have an array of items nodes.
for(var i = 0; i< nodes.length; i++){
var node = nodes[i];
alert(node);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With