Tallaght Campus

Department of Computing

Javascript Loops
  1. Loops

    Loops

    • Loops cause repeated execution of the the same instructions.
    • One execution of the repeated instructions is called an iteration.
    • Iterations can differ between them:
      • different data may be used
      • different branches of execution may be followed depending on conditions
  2. For loops

    For loops

    For loops are used when the number of iterations is known before the loop starts executing, either

    • because the number of iterations is relevant (e.g. we want to pick 6 lottery numbers - the number of iterations is 6)
    • because the iterations are tied to a collection of things (e.g. we want to process a company's orders for the day - yesterday there may have been 15 orders and 25 today, but at the time when we start processing them, we know how many there are)

    For loop syntax

    for ( initialisation-statements ; loop-condition ; end-of-iteration-statements ) {
        loop-statement-block
    }
    characters in blue
    Must appear literally as shown.
    whitespace characters
    Ignored.
    initialisation-statements
    Used to set up any variables needed by the loop. These are called once before the loop starts.
    loop-condition
    Must evaluate to a boolean and is checked just before every iteration. If true, the looping continues. If false the looping stops.
    end-of-iteration-statements
    Executed at the very end of every iteration. Used to prepare any data needed for the next iteration.
    loop-statement-block
    The instructions to be executed in every iteration.

    For loop examples

    1. Print the number 1 ten times to the console

    2. Print the numbers from 1 to 10 to the console

    3. Print 10 random numbers between 1 and 10 to the console

    4. Print the characters of the string "TU Dublin" one by one to the console

    5. Create an HTML file with an input element with id "inword". Inside the HTML file, write a Javascript function (called logCharsOfWord) that writes the characters entered as input, one-by-one, to the console. Call the function from the console to test it.

    6. Create an HTML file with an input element with id "inword", a paragraph element with id "pgph" and a button. In the HTML file, write a Javascript function (called writeCharsOfWord) that writes the characters from the input element into the paragraph element, each preceded by its index in the word (see expected output for word 'hello' to the right of this paragraph). Add the function as handler for the click event on the button.

  3. For/of loops

    For/of loops

    • For/of loops are a variant of for loops and allow iteration through the items in an iterable entity.
    • Each iteration is used to process one of the items.
    • For example, they can be used for iterating through the characters of a string.

    For/of loop syntax

    for ( variable-name of iterable-expression ) {
        loop-statement-block
    }
    characters in blue
    Must appear literally as shown.
    whitespace characters
    Ignored.
    variable-name
    A name for the variable that will contain the current item in every iteration.
    iterable-expression
    An expression that evaluates to an iterable entity of some sort. It can be a literal, a variable or complex expression.
    loop-statement-block
    The instructions to be executed in every iteration. This usually involves doing something with the variable named variable-name.

    For/of loop examples

    1. Revisit for loop example 4, implementing the iteration through the characters of the word with a for/of loop.

    2. Repeat for loop exercise 6 but with the following differences:

      • instead of a paragraph, create an empty unordered list element (ul) and give it the id 'ulst'
      • this time instead preceding each character with a number, the function should write each character as a listed item inside the unordered list (expected output for the word 'hello' is shown to the right of this paragraph)
      • use a for/of loop

      Important note: Make sure that after any HTML-modifying statement is executed, the resulting HTML is valid, otherwise the code may not work.

  4. While loops

    While loops

    While loops are generally used when the number of iterations is not known before the loop starts executing, either

    • because it depends on a random process
    • because it depends on information obtained externally while the loop is executing (e.g. user input)

    While loop syntax

    initialisation-statements
    while ( loop-condition ) {
        loop-statement-block
    }
    characters in blue
    Must appear literally as shown.
    whitespace characters
    Ignored.
    initialisation-statements
    Used to set up any variables needed by the loop.
    loop-condition
    Must evaluate to a boolean and is checked just before every iteration. If true, the looping continues. If false the looping stops.
    loop-statement-block
    The instructions to be executed in every iteration.

    While loop examples

    1. Write a while loop that prints random numbers between 1 and 10 until the number is 10. Sample console output is shown on the right.

      As an additional excercise, write the above loop to use a function in order to avoid repetition of code.

  5. Do/while loops

    Do/while loops

    A do/while loop is similar to the while loop, with the difference that the statement block is executed before the condition is checked for the first time.

    Do/while loop syntax

    initialisation-statements
    do {
        loop-statement-block
    } while ( loop-condition );
    characters in blue
    Must appear literally as shown.
    whitespace characters
    Ignored.
    initialisation-statements
    Used to set up any variables needed by the loop.
    loop-statement-block
    The instructions to be executed in every iteration.
    loop-condition
    Must evaluate to a boolean and is checked just before every iteration. If true, the looping continues. If false the looping stops.

    Do/while loop examples

    1. If we examine while loop example 1, we see that the code that gets a random number and prints it to the console needs to be executed before the condition is checked for the first time. We will now rewrite this scenario to use a do/while loop, which suits it a lot better.

  6. Nested loops

    Nested loops

    Loops can be nested. Either type of loop (while or for) can be the outer loop and either type can be the inner loop.

    Nested loop examples

    1. Write some Javascript code that prints out to the console all combinations of letter and number for letters a, b, c, d and numbers 1, 2, 3. The first three combinations are a1, a2 and a3. Use nested loops

    2. Write a couple of Javascript loops, one nested inside the other, that repeat the random number printing from the first while loop exercise 10 times.

      As an additional exercise, instead of printing the random numbers, count how many 'draws' it takes to get a 10 and print the number of tries (with appropriate text). You should have this printed 10 times, since the 'random number drawing until a 10 is drawn' is repeated 10 times. At the end of it all, print the average number of draws it took (with appropriate text).