All programming languages have built in statements for iterations, aka repetitions. The three basic language constructs for this are (traditionally)
whiledo whilefor
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.
while loop'use strict';
let i = 0;
while (i < 10) {
// code to be repeated
console.log('Rep ' + i);
i++;
}
console.log('after loop ' + i);do while loopBecause 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);
for loop'use strict';
for (var i = 0; i < 10; i++) {
// code to be repeated
console.log('Rep ' + i);
}
console.log('after loop ' + i);n TimesThe three dots are called the spread operator.
const res = [...Array(10)].map( function(_, i) {
return i * 10;
});
console.log(res);
n Times[...Array(10)].forEach( function(_, i) {
console.log(i);
});n Times[...Array(10)].forEach( function() {
console.log('looping 10 times');
});(function rec(n, m) {
if (n >= m) return;
console.log('iteration: ' + n);
rec(n + 1, m);
})(0, 10);