Loops
while
whileFun with loops!
The while loop looks a lot like an if statement. They both execute their associated code block based on the result of their conditional expression. The difference being, the while loop will repeatedly check its conditional expression and continue to run its code block as long as it evaluates to true. Give it a try:
let n = 0;
console.log("I am called the Count... because I really love to count!");
while (n < 10) {
console.log(n, "ha-ha-ha");
n++;
}
console.log("fin!");Exercise 1
Looping in the developer tools
Work through the following exercises as a group, implementing each in your developer console when viewing your landing page.
EXERCISE 1: Create a
whileloop that logs numbers 1 through 10 to the console. HINT:EXERCISE 2: Create a
whileloop that logs every even number from 2 through 20 to the console. HINT:EXERCISE 3: Create a
whileloop thatconsole.logs a running total of the cumulative sum of numbers from 1 ton. HINT:EXERCISE 4: Then, in addition to
console.log-ing each iteration, append all lists to the document body. HINT (for exercise 1... try the others on your own):EXERCISE 5: We can also combine
ifandelsestatements in our loops to respond to different input states. For this exercise, count down from 15 by ones. For each number, log "even" or "odd" to the console and to a new div for Exercise 5. HINT:EXERCISE 6: Let's extend the idea of
ifandelseinwhileloops with a pretty common exercise called FizzBuzz. For this exercise, log and output "Fizz" if a number is divisible by 3, "Buzz" if a number by 5, and "FizzBuzz" if a number is divisible by both 3 and 5. If a number is not divisible by 3 or 5, then just output the number. For this exercise, count up from 1 to 100. HINT:
Portfolio Project 1
Better Navigation with while
whileWhen we left off, our SPA's navigation code looked something like this:
Not the worst code in the world, but it had two big problems: first, there could only ever be three navigation links (no more, no less). And those navigation links couldn't change like our page title could. Let's see if we can make this code cleaner and more versatile with a while loop.
Use a
whileloop to add aclickevent listener to every anchor tag in thenavigationelement.Much better! And what about varying the links themselves? How about letting our
Navigationextract those from ourstates. InNavigation.js:Then we just need to include an Array of
linksin each state Object. Give it a try!
Last updated