# Loops
First, lets review why we have loops. They are a common feature in programming languages. Say, for example, that you wanted to create a list of five random numbers. You could declare five variables and use the Math.random( )
method to generate the numbers and assign them to the variables. We could do this with just repeating the same line of code five times.
var num1 = Math.random();
var num2 = Math.random();
var num3 = Math.random();
var num4 = Math.random();
var num5 = Math.random();
2
3
4
5
While a bit tedious, you can do this without too much effort.
Now, imagine that you need to save a thousand random numbers, or ten thousand. That would be a LOT of code to write. Loops are a programmatic way of accomplishing a similar task in a repetitive manner with minimal code. Here is an example that would generate 100,000 random numbers and save them all in an Array.
var nums = [];
for (var i = 0; i < 100000; i++) {
nums.push(Math.random());
}
2
3
4
That's it. Four lines of code. 100,000 random numbers generated and saved in an Array.
# for loops
for (var i = 0; i < 10; i++) {
console.log(i);
}
2
3
# for...in loops
for (prop in myObject) {
console.log(myObject[prop]);
}
2
3
# while loops
There are two kinds of while loops in JavaScript, the while loop and the do..while loop. The difference between them is that the do..while loop will always run at least once because it runs the loop before checking to see if the while test passes. The while loop will test your condition before it runs the loop.
var counter = 0;
while (counter < 10) {
console.log(counter);
counter++;
}
var counter2 = 0;
do {
console.log(counter2);
counter2++;
} while (counter2 < 10);
2
3
4
5
6
7
8
9
10
11
# For...of loops
These are closely related to for...in loops but let you target the value without having to use dot notation or the square bracket syntax. If you don't need the index number of the array or the property name from the object then this might be of value to you.
There is a difference between for...in
and for...of
in that for...of
cannot loop over most Objects. This has to do with the difference between Iterable
and Enumerable
, which we will talk about later.
For those of you who are keen to understand this now: