JavaScript Loops Worksheet
Questions
Question 1
What is the difference between a while loop and a for loop?
"While Loops" keep on running the script until the value becomes a specific value. "For Loops" will keep on running the first and third parameters until the second parameter is false.
Examples:
While Loops- while(value = true) or while(value1 != value2)
For Loops- for(x = 1; x < 5; x++)
Examples:
While Loops- while(value = true) or while(value1 != value2)
For Loops- for(x = 1; x < 5; x++)
Question 2
What is an iteration?
The code processes all of the information from an array and runs it within a for loop. Normally printing out the information.
Example:
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++){
console.log(numbers[i]);
}
Example:
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++){
console.log(numbers[i]);
}
Question 3
What is the meaning of the current element in a loop?
The current element is the item in the [] after the element value. It tells the program what value of the element to take and use.
Example:
const letters = [a, b, c, d, e];
for (let i = 0; i < letters.length; i++){
console.log(letters[i]);
}
The [i] tells the console which place within the "letters" element will be used.
If i = 0, letters[0] = a
If i = 1, letters[1] = b
If i = 2, letters[2] = c
The values within "letters" need to be defined for it to work though.
Example:
const letters = [a, b, c, d, e];
for (let i = 0; i < letters.length; i++){
console.log(letters[i]);
}
The [i] tells the console which place within the "letters" element will be used.
If i = 0, letters[0] = a
If i = 1, letters[1] = b
If i = 2, letters[2] = c
The values within "letters" need to be defined for it to work though.
Question 4
What is a 'counter variable'?
A counter variable is a variable that keeps track of how many times a loop has been executed.
Question 5
What does the break; statement do when used inside a loop?
"Break" ends the loop and jumps to the next step within the program.
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.