Features in Web Applications: The For Loop Flashcards
1
Q
For Loop
A
- The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed
} - Statement 1 is executed (one time) before the execution of the code block.
- Statement 2 defines the condition for executing the code block.
- Statement 3 is executed (every time) after the code block has been executed.
2
Q
statement 1
A
- Normally you will use statement 1 to initialize the variable used in the loop (i = 0).
- This is not always the case, JavaScript doesn’t care. Statement 1 is optional.
- You can initiate many values in statement 1 (separated by comma):
- Example
for (i = 0, len = cars.length, text = “”; i < len; i++) {
text += cars[i] + “<br></br>”;
}
3
Q
statement 2
A
- Often statement 2 is used to evaluate the condition of the initial variable.
- This is not always the case, JavaScript doesn’t care. Statement 2 is also optional.
- If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
- If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.
4
Q
statement 3
A
- Often statement 3 increments the value of the initial variable.
- This is not always the case, JavaScript doesn’t care, and statement 3 is optional.
- Statement 3 can do anything like negative increment (i–), positive increment (i = i + 15), or anything else.
- Statement 3 can also be omitted (like when you increment your values inside the loop):
- Example
var i = 0;
var len = cars.length;
for (; i < len; ) {
text += cars[i] + “<br></br>”;
i++;
}
5
Q
In the string: “Hello There, Kim!” the “K” represents which letter position?
A
13
6
Q
What do you think the general purpose of loops is?
A
In essence, it’s to repeat a set of programming instructions to save us typing many repetitive lines of code and making our programs more efficient.