Loops

A loop is used to execute a block of code repeatedly as long as a specified condition is satisfied, or until a stopping condition is reached.

For example, imagine you want to print "hello students" 10 times. Instead of writing console.log() ten times, you can use a loop.


JavaScript has three commonly used loops:


1. for loop

Used when you know how many times you want to repeat something.

Example: Display 10 student names.


2. while loop

Used when repetition depends on a condition, and the number of repetitions may not be known beforehand.

Example: Continue a game while the player has lives remaining.


3. do...while loop

Used when the code must execute at least once, even if the condition is false.

Example: Show a menu at least once and then ask whether to continue.