JavaScript Loops Worksheet

Questions

Question 1

What is the difference between a while loop and a for loop?

A while loop just has a condition and keeps running while that condition is true, but a for loop puts the setup, condition, and update of the counter all together in one line.

Question 2

What is an iteration?

An iteration is a single time the loop body runs from top to bottom.

Question 3

What is the meaning of the current element in a loop?

The current element is the specific item in the list or collection that the loop is working on during that particular iteration.

Question 4

What is a 'counter variable'?

A counter variable is a number variable that keeps track of how many times the loop has run or which position you are at.

Question 5

What does the break; statement do when used inside a loop?

The break; statement immediately stops the loop and jumps to the first line of code after 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 gets all the h4 elements on the page, then loops through them and logs the innerHTML to the console one by one.

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.