2024/2025
- ANSWERSLoops can execute a block of code a number of times.
JavaScript Loops - ANSWERSJavaScript Loops
- ANSWERSLoops are handy, if you want to run the same code over and over again, each time with a
different value.
- ANSWERSOften this is the case when working with arrays:
- ANSWERSInstead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
Different Kinds of Loops - ANSWERSDifferent Kinds of Loops
- ANSWERSJavaScript supports different kinds of loops:
, for - loops through a block of code a number of times
for/in - loops through the properties of an object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
The For Loop - ANSWERSThe For Loop
- ANSWERSThe for loop is often the tool you will use when you want to create a loop.
- ANSWERSThe for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed
}
- ANSWERSStatement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
- ANSWERSExample
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
- ANSWERSFrom the example above, you can read:
Statement 1 sets a variable before the loop starts (var i = 0).