JavaScript Loops Worksheet
Questions
Question 1
What is the difference between a while loop and a for loop?
A 'while loop' runs as long as the condition is true. This is good for when you are not sure how many times a loop needs to be used.
A 'for loop' runs for set number of times.
Example: 'while loop'
Example: 'for loop'
A 'for loop' runs for set number of times.
Example: 'while loop'
let counter = 0;
while (counter < 5){
console.log("counter is:", counter);
counter++; // updates the condition manually
}
Example: 'for loop'
for (let counter = 0; counter < 5; counter++){
console.log("counter is:", counter);
}
Question 2
What is an iteration?
An iteration refers to a complete cycle of a process, meaning that it refers to a block a code being executed once as part of a loop's repeated operation.
Example:
Example:
for (let i = 0; i < 3; i++){
console.log("iteration:", i);
}
For this example, the loop runs three times:
- first iteration: i = 0
- second iteration: i = 1
- third iteration: i = 2
Question 3
What is the meaning of the current element in a loop?
The current element in a loop is the 'value' that is being processed during that specific round of the loop. Essentially, it is just the value the loop is working with at the moment.
Example: in an array, as shown below, each number [10, 20, 30] is the current element as the loop runs.
Example: in an array, as shown below, each number [10, 20, 30] is the current element as the loop runs.
let numbers = [10, 20, 30];
for (let i = 0; i < numbers.length; i++) {
console.log("Current element:", numbers[i]); // current element at each iteration
}
- first iteration: 10
- second iteration: 20
- third iteration: 30
Question 4
What is a 'counter variable'?
A counter variable keeps track of how many times something happens, such as counting loop iterations.
Question 5
What does the break; statement do when used inside a loop?
The 'break' statement stops a loop, ignoring the condition. The program then continues with the code after the loop.
Example:
Example:
for (let i = 0; i < 5; i++){
if (i === 3){
break; // exits the loop when i = 3
}
console.log(i);
}
Output:
- 0
- 1
- 2
Coding Problems
Coding Problems - See the 'script' tag below this h3 tag. You will have to write some JavaScript code in it.
Always test your work! Check the console log to make sure there are no errors.