while Loop Syntax
Something, usually a statement within the
while block, must cause the condition to change so that it eventually becomes false and causes the loop to end. Otherwise, you get stuck in an infinite loop, which can bring down the browser.
do...while Loop Syntax
Again something, usually a statement within the
do block, must cause the condition to change so that it eventually becomes false and causes the loop to end.
while loops, the statements in
do...while loops will always execute at least one time because the conditions are not checked until the end of each iteration.
for Loop Syntax
In for loops, the initialization, conditions, and change are all placed up front and separated by semi-colons. This makes it easy to remember to include a change statement that will eventually cause the loop to end.
for loops are often used to iterate through arrays. The
length property of an array can be used to check how many elements the array contains.
for...in Loop Syntax
for...in loops are specifically designed for looping through arrays.
For reasons that will be better understood when we look at object augmentation,
the above syntax has a slight flaw. If the
Array class is changed, it
is possible that the
for...in loop includes more items than what you
To be on the safe side, we suggest that you use a more verbose syntax as seen below.
hasOwnProperty() call will ensure that the item is indeed
an element that you added to the array, not something that was inherited
because of object augmentation.
for...of Loop Syntax
for...of loops are a recent addition to JavaScipt, allowing us to loop through any iterable object - objects of classes like
Set, and other similar classes - rather than just arrays. (An interable object is an object of a class that is enumerable, where the elements are in a definite order.) As
for...of loops aren't supported by all browsers, you might avoid this loop type for now - but a good construct for you to recognize should you see it in the code.