Loops in JavaScript
Learn how to repeat code efficiently using loops.
Why Use Loops?
Loops allow you to execute a block of code multiple times. Instead of writing repetitive code, you can use a loop to automate the process.
The for Loop
The for loop is the most common loop. It has three parts: initialization, condition, and increment.
Looping Through Arrays
One of the most common uses of loops is iterating through arrays.
The while Loop
The while loop continues as long as a condition is true. Be careful to avoid infinite loops!
The do...while Loop
The do...while loop is similar to while, but it always executes at least once.
The forEach Method
Arrays have a built-in forEach method that's a cleaner way to iterate.
Break and Continue
Use break to exit a loop early and continue to skip to the next iteration.
Challenge: FizzBuzz
Write a loop that prints numbers from 1 to 20. But for multiples of 3, print "Fizz" instead. For multiples of 5, print "Buzz". For multiples of both 3 and 5, print "FizzBuzz".