-
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
-
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
-
Print the number 1 ten times to the console
// Note: ++i is the same as i += 1 for (let i = 0; i < 10; ++i) { console.log(1); }
-
Print the numbers from 1 to 10 to the console
for (let i = 0; i < 10; ++i) { console.log(i); }
-
Print 10 random numbers between 1 and 10 to the console
for (let i = 0; i < 10; ++i) { console.log(Math.floor(Math.random() * 10) + 1); }
-
Print the characters of the string "TU Dublin" one by one to the console
const text = "TU Dublin"; for (let i = 0; i < text.length; ++i) { console.log(text.charAt(i)); }
-
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.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Document</title> </head> <body> <input type="text" id="inword"> <script> function logCharsOfWord() { let word = document.getElementById("inword").value; for (let i = 0; i < word.length; ++i) { console.log(word[i]); } } </script> </body> </html>
-
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.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Document</title> </head> <body> <input type="text" id="inword"> <button type="button" onclick="writeCharsOfWord()"> Write characters </button> <p id="pgph"></p> <script> function writeCharsOfWord() { let word = document.getElementById("inword").value; let paragraphElement = document.getElementById("pgph"); paragraphElement.innerHTML = ""; for (let i = 0; i < word.length; ++i) { paragraphElement.innerHTML += i + " " + word[i] + "<br/>"; } } </script> </body> </html>
-
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
Revisit for loop example 4, implementing the iteration through the characters of the word with a for/of loop.
const text = "TU Dublin"; for (c in text) { console.log(c); }
-
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.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Document</title> </head> <body> <input type="text" id="inword"> <button type="button" onclick="writeCharsOfWord()"> Write characters </button> <ul id="ulst"></ul> <script> function writeCharsOfWord() { let word = document.getElementById("inword").value; let ulElement = document.getElementById("ulst"); ulElement.innerHTML = ""; for (c of word) { ulElement.innerHTML += "<li>" + c + "</li>"; } } </script> </body> </html>
-
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
-
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.
let randNum = Math.floor(Math.random() * 10) + 1; console.log(randNum); while (randNum != 10) { randNum = Math.floor(Math.random() * 10) + 1; console.log(randNum); }
As an additional excercise, write the above loop to use a function in order to avoid repetition of code.
function rand1To10 () { let r = Math.floor(Math.random() * 10) + 1; console.log(r); return r; } let randNum = rand1To10(); while (randNum != 10) { randNum = rand1To10(); }
OR
function goAgain() { let r = Math.floor(Math.random() * 10) + 1; console.log(r); return r != 10; } while (goAgain()) {}
-
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
-
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.
let randNum; do { randNum = Math.floor(Math.random() * 10) + 1; console.log(randNum); } while (randNum != 10);
-
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
-
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
const letters = "abcd"; for (let l = 0; l < letters.length; ++l) { for (let i = 1; i < 4; ++i) { console.log(letters[l] + i); } }
-
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.
for (let i = 0; i < 10; ++i) { let randNum = Math.floor(Math.random() * 10) + 1; console.log(randNum); while (randNum != 10) { randNum = Math.floor(Math.random() * 10) + 1; console.log(randNum); } }
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).
let sum = 0; for (let i = 0; i < 10; ++i) { let randNum = Math.floor(Math.random() * 10) + 1; let count = 1; while (randNum != 10) { randNum = Math.floor(Math.random() * 10) + 1; ++count; } sum += count; console.log("Number of draws in round " + i + ": " + count); } console.log("Average number of draws: " + sum/10);
-
-
Loops
-
For loops
-
For/of loops
-
While loops
-
Do/while loops
-
Nested loops