Practice and reinforce the concepts from Lesson 5
Total Time: 45-60 minutes
:warning: Warning DO NOT DELETE the existing files in the template:
- Package files
- Any other files you didn't create
ONLY EDIT the necessary files.
Objective: Write a program that logs "giraffe" 5 times using a for loop
Instructions:
i
and set it to 1i
is less than or equal to 5
(use <=
)i++
:bulb: Tip Loop Structure:
for(i=1; i<=5; i++) { console.log("giraffe"); }
Be careful with your conditions! Double-check before running to avoid infinite loops that can crash your browser.
Expected Output:
Objective: Write a program that logs only even numbers from 1 to 10 using a for loop
Instructions:
i
and set it to 1i
is less than or equal to 10
(use <=
)i++
i
is even:bulb: Tip Even Number Check: Use the modulus operator
%
to check if a number is even:
if (i % 2 === 0) {
// This number is even
}
Expected Output:
Objective: Write a program that counts down from 20 by steps of 5 using a while loop
Instructions:
i
and set it to 20i > 0
i
i
by 5 (use i = i - 5
):bulb: Tip While Loop Structure:
while(i > 0) {
console.log(i);
i = i - 5;
}
Remember to update your variable inside the loop, or it will run forever!
Expected Output:
Objective: Write a program that counts from 1 to 7 using a do-while loop
Instructions:
i
and set it to 1i
i
by 1 (use i++
)i <= 7
:bulb: Tip Do-While vs While: A do-while loop always executes at least once before checking the condition. This is useful when you need to run code at least one time regardless of the condition.
Expected Output:
Objective: Create a PIN guessing game that allows exactly 4 attempts using a for loop with break
Instructions:
i <= 4
)prompt()
to ask "What is the four digit pin number?"break
to exit:bulb: Tip Using Break: The
break
statement immediately exits the loop when the correct PIN is entered:
if (guess === correctPin) {
alert("Unlocked!");
break; // Exit the loop early
}
Expected Outputs:
Step 1 - PIN Prompt:
Step 2 - Wrong PIN Alert:
Step 3 - Correct PIN Alert:
Before submitting, ensure your projects include:
:warning: Warning Infinite Loop Prevention:
- Always double-check your loop conditions before running
- Make sure your update statement changes the loop variable
- Use browser's stop/reload button if stuck in an infinite loop
:bulb: Tip Debugging Tips:
console.log()
statements to track your loop variable<
, >
, <=
, >=
) are correct:information_source: Ready to submit? Make sure you've:
- Completed all 5 exercises
- Tested each loop to verify correct output
- Checked that no infinite loops occur
Great job completing your loop exercises! These fundamental concepts will be essential for creating dynamic and interactive JavaScript applications.