There are several kinds of traditional loops in JavaScript which are used considerably less since the introduction of various newer array iteration methods.
Nonetheless for
, while
and do .. while
loops are still extremely useful.
for loops
for loops start like if statement with a regular bracket: for ( .... ) {
The basic syntax is:
for ( conditions to be met ) {
...run some code
}
Those conditions inside the brackets are to create a counter:
for (let i = 0; i < 21; i++) {
// do this
}
The counter
The three conditions that need to be met are called the initializer, the condition and the final expression.
First a variable is defined for the counter and a starting point, let i = 0;
.
Next the variable is given a maximum number. As always the count starts with zero so less than 3 is actually 3 counts (0, 1, 2): i < 3;
The third part adds to the variable each time: i++
.
Here’s an example that goes through the array firstName
.
for (let i = 0; i < 5; i++) {
if (firstName[i] === "John") {
alert("hello " + firstName[i]);
}
}
NB i
is usually used as a convention standing for iteration. However any variable name is fine.
To stop a loop from going on past where it needs to add the word break;
Sometimes you need to create flags which are variables, usually containing boolean values.
var x = false;
While loops
while
loops in JavaScript are the simplest of all. They work like an if
statement and the syntax is much the same. The loop runs while
a condition, in parentheses, is true.
In the first example the loop executes the block of code as long as the variable i
is less than 10. Each time through the loop the value of i
is increased by 1: i++
.
let i = 0;
while (i < 10) {
console.log(`while loop no. ${i}`);
i++;
}
In the above example the loop is broken when i
exceeds 10. All loops must have a way to stop, that is the condition to be false. If they don’t then you get an infinite loop which carries on indefinitely and may crash the computer.
Do .. while loops
The do .. while
loop is very similar to while
loops. The difference is that the syntax is reversed. Here the code executes first before the condition to be met.
This means the loop will always run at least once even if the condition is never true.
do {
alert(`do .. while loop no. ${i}`);
i++;
} while (
i < 4;
)
for … of loops
This is a simpler, newer way to create a loop for looping through arrays.
const myArray = ['dog', 'bear', 'civet', 'mongoose'];
for (let item of myArray) {
console.log(item);
};
NB. The word item
can be any valid string as long as it’s the same in both places.
Don’t confuse these with for ... in
loops which are similar but for objects.
for (let item of shit) {
document.getElementById('shitlist').innerHTML += `${item} 1 <br>`
}
NB. myArray
is the name of the array to loop over. The word item
could be anything. It does not matter other than it’s the same in both places.
High order array methods
Another way of looping through arrays is with array iteration methods like forEach()
.
forEach()
map()
filter()
reduce()
Links
- Tania Rascia has an excellent article on for loops. Also on while / do loops.