Loops are programming constructs that execute a block of code multiple times based on a specific condition or set of conditions. In JavaScript, there are several types of loops, including the 'while' loop that executes code as long as a condition is true, and the 'do … while' loop which ensures the code runs at least once before checking the condition. The 'for' loop provides a concise way to iterate through a sequence, specifying initialization, condition, and afterthought (like incrementing). Additionally, there are special operators such as 'break', which immediately exits the loop, and 'continue', which skips the rest of the current iteration and proceeds to the next one. Nested loops occur when a loop is placed inside another loop, allowing for complex iteration patterns.
Repeating a Statement While Given Condition Holds
while (condition) {
statements;
}
var counter = 0;
while (counter < 10) {
console.log('Number : ' + counter);
counter+=1;
}
Calculate and print the sum of the first N natural numbers
var nStr = '123',
n = +nStr,
number = 1,
sum = 1,
result = 'The sum 1';
while (number < n) {
number += 1;
sum += number ;
result += '+' + number;
}
result += ' = ' + sum;
console.log(result);
Checking whether a number is prime or not
var numberStr = '123';
var number = +numberStr;
var divider = 2;
var maxDivider = Math.sqrt(number);
var prime = true;
while (prime && (divider <= maxDivider)) {
if (!(number % divider)) {
prime = false;
}
divider++;
}
print('output-tb',prime);
break operator exits the inner-most loop
var numberStr = '123‘,
n = +numberStr,
fact = 1,
factStr = 'n! = ';
while (1) { //infinite loop
if (n === 1) {
break;
}
factStr += n + '*'
fact *= n;
n -= 1;
}
factStr += '1 = ' + fact;
console.log(factStr);
do {
statements;
} while (condition);
Calculating N factorial
var fact = 1,
factStr = 'n! = ';
do {
fact *= n;
factStr += n + '*'
n -= 1;
} while (n);
factStr += ' = ' + fact;
console.log(factStr)
Calculating the product of all numbers in the interval [n..m]:
var number = n,
product = 1,
productStr = '';
do {
product *= number;
productStr += number;
if (number != m) {
productStr += '*';
}
number += 1;
} while (number <= m);
productStr += ' = ' + product;
console.log(productStr);
for (initialization; test; update) {
statements;
}
var number = 0
)for (var number = 0; number < 10; number += 1) {
// Can use number here
}
// Cannot use number here
number < 10
)for (var number = 0; number < 10; number += 1) {
// Can use number here
}
// Cannot use number here
number += 1
)for (var number = 0; number < 10; number += 1) {
// Can use number here
}
// Cannot use number here
A simple for-loop to print the numbers 0…9:
var number;
for (number = 0; number < 10; number += 1) {
console.log(number + ' ');
}
<span style=“color:#EBFFD2”> A simple for-loop to calculate n!: </span>
var factorial = 1,
i;
for (i = 1; i <= n; i += 1) {
factorial *= i;
}
Complex for-loops could have several counter variables:
var i, sum;
for (i=1, sum=1; i<=128; i=i*2, sum+=i) {
console.log('i=' + i + ', sum=' +sum);
}
Result:
i=1, sum=1
i=2, sum=3
i=4, sum=7
i=8, sum=15
...
Calculating n to power m (denoted as n^m ):
var result = 1,
i;
for (i = 0; i < m; i += 1) {
result *= n;
}
console.log(result);
for (initialization; test; update) {
for (initialization; test; update) {
statements;
}
…
}
var resultStr = '',
row, col;
for(row = 1; row <= n; row += 1) {
for(column = 1; column <= row; column += 1) {
resultStr += column + ' ';
}
resultStr += '\n';
}
console.log(resultStr);
Print all prime numbers in the interval [n, m]:
var result='',
number, isPrime, divider, maxDivider;
for (number = n; number <= m; number++) {
isPrime = true;
divider = 2;
maxDivider = Math.sqrt(number);
while (divider <= maxDivider) {
if (!(number % divider)) {
isPrime = false;
break;
}
divider += 1;
}
if (isPrime) {
result += number + ' ';
}
}
Print all four digit numbers in format ABCD such that A + B = C + D (known as happy numbers)
var a, b, c, d
for (a =1 ; a <= 9; a += 1) {
for (b = 0; b <= 9; b += 1)
for (c = 0; c <= 9; c += 1)
for (d = 0; d <= 9; d += 1)
if (a + b == c + d)
console.log('{0}{1}{2}{3}',
a, b, c, d);
}
Print all combinations from TOTO 6/49
(Warning: execution of this code could take too long time.)
var i1, i2, i3, i4, i5, i6;
for (i1 = 1; i1 <= 44; i1+=1)
for (i2 = i1 + 1; i2 <= 45; i2+=1)
for (i3 = i2 + 1; i3 <= 46; i3+=1)
for (i4 = i3 + 1; i4 <= 47; i4+=1)
for (i5 = i4 + 1; i5 <= 48; i5+=1)
for (i6 = i5 + 1; i6 <= 49; i6+=1)
console.log('{0} {1} {2} {3} {4} {5}',
i1, i2, i3, i4, i5, i6);
var arr = [1, 2, 3, 4, 5, 6],
index;
for(index in arr) { console.log(arr[index]); }
//1, 2, 3, 4, 5, 6
var prop;
for(prop in document) { console.log(document[prop]); }
//http://localhost:64765/xxx%20for-in-loop.html
//function querySelector() { [native code] }
//function querySelectorAll() { [native code] }
//function evaluate() { [native code] }
var arr = ['One', 'Two', 'Three', 'Four'];
for(var n of arr) {
console.log(n);
}
//prints 'One', 'Two', 'Three' and 'Four'