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.

Pro Tip: Loops are essential for working with arrays and collections of data. Master them early!

The for Loop

The for loop is the most common loop. It has three parts: initialization, condition, and increment.

Try it yourself
Output

Looping Through Arrays

One of the most common uses of loops is iterating through arrays.

Try it yourself
Output

The while Loop

The while loop continues as long as a condition is true. Be careful to avoid infinite loops!

Try it yourself
Output
Warning: Always ensure your while loop has a way to end. An infinite loop can crash your browser!

The do...while Loop

The do...while loop is similar to while, but it always executes at least once.

Try it yourself
Output

The forEach Method

Arrays have a built-in forEach method that's a cleaner way to iterate.

Try it yourself
Output

Break and Continue

Use break to exit a loop early and continue to skip to the next iteration.

Try it yourself
Output

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".

Your solution
Output