Iterations

All programming languages have built in statements for iterations, aka repetitions. The three basic language constructs for this are (traditionally)

The former two are the originals, the latter was invented to make it difficult to make certain errors with while. Whatever can be done with while can also be done with for, and vice versa.

As Long As, while

Example 6.1. Schematic View of the while loop
'use strict';
let i = 0;
while (i < 10) {

    // code to be repeated
    console.log('Rep ' + i);

    i++;
}

console.log('after loop ' + i);

A Variant of While, do while

Example 6.2. Schematic View of the do while loop

Because of the usefulness of arrays you may frequently decide to use them dynamically for storing values that are dependent on user input, or as results of some process that you program is doing. Let us for example pretend that the users are encouraged to enter long words, and you need your program to store the words. If a word is already there, we will skip it.

'use strict';
let wordlist = [];
let word = '';
do {
    if (word === '9')   // exit loop on a nine
        break;
    if (word === '')    // ignore empty strings
        continue;
    if (wordlist.indexOf(word) !== -1) // is word already there
        continue;
    wordlist.push(word);    // push word onto array
    console.log('There\'s now ' + wordlist.length + ' words in the list');
} while (word = prompt('Enter a good long word'));

console.log(wordlist);
wordlist.sort();
console.log(wordlist);

The Counting Loop, for

Example 6.3. Schematic View of the for loop
'use strict';
for (var i = 0; i < 10; i++) {

    // code to be repeated
    console.log('Rep ' + i);

}

console.log('after loop ' + i);

Later JavaScript Inventions

Example 6.4. An ES6 Iteration: Do n Times

The three dots are called the spread operator.

const res = [...Array(10)].map( function(_, i) {
        return i * 10;
    });
console.log(res);

Example 6.5. Another ES6 Iteration: Do n Times
[...Array(10)].forEach( function(_, i) {
        console.log(i);
    });

Example 6.6. An ES6 Iteration: Do n Times
[...Array(10)].forEach( function() {
        console.log('looping 10 times');
    });

Example 6.7. Not ES6, Yours Truly
(function rec(n, m) {
        if (n >= m) return;
        console.log('iteration: ' + n);
        rec(n + 1, m);
    })(0, 10);