Aside form the build-in loops (while() ...
, do ... while()
, for() ...
), there is a structure of self calling function, also known as recursion to create a loop without the three build-in loop structures.
Consider the following:
// set the initial value
var loopCounter = 3;
// the body of the loop
function loop() {
// this is only to show something, done in the loop
document.write(loopCounter + '
');
// decrease the loopCounter, to prevent running forever
loopCounter--;
// test loopCounter and if truthy call loop() again
loopCounter && loop();
}
// invoke the loop
loop();
Needless to say that this structure is often used in combination with a return value, so this is a small example how to deal with value that is not in the first time available, but at the end of the recursion:
function f(n) {
// return values for 3 to 1
// n -n ~-n !~-n +!~-n return
// conv int neg bitnot not number
// 3 -3 2 false 0 3 * f(2)
// 2 -2 1 false 0 2 * f(1)
// 1 -1 0 true 1 1
// so it takes a positive integer and do some conversion like changed sign, apply
// bitwise not, do logical not and cast it to number. if this value is then
// truthy, then return the value. if not, then return the product of the given
// value and the return value of the call with the decreased number
return +!~-n || n * f(n - 1);
}
document.write(f(7));