JavaScript Loops Worksheet
Questions
Question 1
What is the difference between a while loop and a for loop?
A while loop repeats as long as its condition is true.
A for loop is used when you know how many times you want to loop — it includes the counter setup, condition, and update all in one line.
Question 2
What is an iteration?
An iteration is one single time a loop runs — one full pass through the loop body.
Question 3
What is the meaning of the current element in a loop?
The current element is the item in an array or list that the loop is looking at during that specific iteration.
Question 4
What is a 'counter variable'?
A counter variable is a variable that keeps track of how many times a loop has run, usually increased every iteration.
Question 5
What does the break; statement do when used inside a loop?
The break statement immediately stops the loop, even if the loop’s condition is still true.
Question 6
Explain what the following code is doing:
const allH4elements = document.getElementsByTagName("h4");
for(let x = 0; x < allH4elements.length; x++){
console.log(allH4elements[x].innerHTML);
}
This code selects every <h4> element on the page and loops through them.
During each iteration, it logs the text (innerHTML) inside each <h4> tag to the console.
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.