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.

Topics covered:

  • What is a Loop?
  • Loops in JavaScript
    • while loops
    • dowhile loops
    • for loops
  • Special loop operators
    • break, continue
  • Nested loops

Video (in Bulgarian)

Presentation Content

What Is Loop?

  • A loop is a control statement that allows repeating execution of a block of statements
    • May execute a code block fixed number of times
    • May execute a code block while given condition holds
    • May execute a code block for each member of a collection
  • Loops that never end are called an _infinite _ loops

How To Use While Loop?

Repeating a Statement While Given Condition Holds

  • The simplest and most frequently used loop
    while (condition) {
        statements;
    }
    
  • The repeat condition
    • Also called loop condition
    • Is not necessary true or false
    • Is evaluated to true or false
      • 5, “non-empty”, etc.. are evaluated as true
      • <span style=“color:#EBFFD2”>0, “”, null are evaluated as false</span>

While Loop – Example

var counter = 0;
while (counter < 10) {
    console.log('Number : ' + counter);
    counter+=1;
}

Sum 1…N – Example

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);

Prime Number – Example

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);

Using break Operator

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);

Using Do-While Loop

  • Another loop structure is:
    do {
        statements;
    } while (condition);
    
  • The block of statements is repeated
    • While the boolean loop condition holds
  • The loop is executed at least once

Factorial – Example

Calculating N factorial

var fact = 1,
    factStr = 'n! = ';
do {
fact *= n;
factStr += n + '*'
n -= 1;
} while (n);
factStr += ' = ' + fact;
console.log(factStr)

Product[N…M] – Example

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 Loops

  • The typical for loop syntax is:
    for (initialization; test; update) {
        statements;
    }
    
  • Consists of
    • Initialization statement
    • Test expression that is evaluated to boolean
    • Update statement
    • Loop body block

The Initialization Expression (var number = 0)

for (var number = 0; number < 10; number += 1) {
    // Can use number here
}
// Cannot use number here
  • Executed once, just before the loop is entered
    • Like it is out of the loop, before it
  • Usually used to declare a counter variable

The Test Expression (number < 10)

for (var number = 0; number < 10; number += 1) {
    // Can use number here
}
// Cannot use number here
  • Evaluated before each iteration of the loop
    • If evaluated true , the loop body is executed
    • If evaluated false , the loop body is skipped
  • Used as a loop condition

The Update Expression (number += 1)

for (var number = 0; number < 10; number += 1) {
    // Can use number here
}
// Cannot use number here
  • Executed at each iteration after the body of the loop is finished
  • Usually used to update the counter

Simple for Loop – Example

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 Loop – Example

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
...

N^M – Example

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);

What Is Nested Loop?

  • A composition of loops is called a nested loop
    • A loop inside another loop
  • Example:
    for (initialization; test; update) {
        for (initialization; test; update) {        
            statements;
        }
        …
    } 
    

Triangle – Example

  • Print the following triangle:
    • 1
    • 1 2
    • 1 2 3 ... n
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);

Primes[N, M] – Example

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 + ' ';
    }
}

Nested Loops – Examples

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);      

for-in Loop

  • for-in loop iterates over the properties of an object
    • When the object is array , nodeList or liveNodeList for-in iterates over their elements
    • When the object is not an array, for-in iterates over its properties
  • Iterating over the elements of an array
    var arr = [1, 2, 3, 4, 5, 6],
        index;
    for(index in arr) { console.log(arr[index]); }
    //1, 2, 3, 4, 5, 6
    
  • Iterating over the properties of document
    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] }
    

The for-of loop

  • The for-of loop iterates over the elements in an array
    • Can be used only on arrays, or array-like objects
      • i.e. the arguments object
      var arr = ['One', 'Two', 'Three', 'Four'];
      for(var n of arr) { 
        console.log(n); 
      }
      //prints 'One', 'Two', 'Three' and 'Four'
      
  • The for-of loop is part of the ECMAScript 6 standard
    • Supported in all modern browsers