JavaScript Loops Worksheet
Questions
Question 1
What is the difference between a while loop and a for loop?
The difference between a while loop and a for loop is that a while loop continues to execute as long as a specified condition is true, whereas a for loop is typically used when the number of iterations is known beforehand, allowing initialization, condition, and increment/decrement to be defined in one line.
Question 2
What is an iteration?
An iteration is a single cycle or pass through the loop's body, where the loop executes its code once.
Question 3
What is the meaning of the current element in a loop?
The current element in a loop refers to the specific item or value that the loop is currently processing or accessing during its iteration.
Question 4
What is a 'counter variable'?
A counter variable is a variable used to keep track of the number of iterations or to control the number of times a loop executes. It is typically initialized before the loop starts and updated within the loop.
Question 5
What does the break; statement do when used inside a loop?
The break; statement, when used inside a loop, immediately terminates the loop, causing the program to exit the loop and continue executing the code that follows the loop.
Question 6
Explain what the following code is doing (if you would like to run this code, you can paste it into the SCRIPT element in the page):
const allH4elements = document.getElementsByTagName("h4");
for(let x = 0; x < allH4elements.length; x++){
console.log(allH4elements[x].innerHTML);
}
This code retrieves all the elements in the document using document.getElementsByTagName("h4") and stores them in the allH4elements variable. It then uses a for loop to iterate through each
elements in the document using document.getElementsByTagName("h4") and stores them in the allH4elements variable. It then uses a for loop to iterate through each element, logging the innerHTML (the content inside the tags) of each element to the console.
tags) of each element 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.