JavaScript Loops

Loops are fundamental programming structures that allow you to execute a block of code multiple times. They are extremely useful when you want to automate repetitive tasks or iterate over collections like arrays or objects.

📌 Why Use Loops?

  • Reduce repetitive code and improve maintainability
  • Iterate over data structures like arrays, objects, and maps
  • Perform repeated calculations efficiently
  • Enable automation in web applications, such as generating lists dynamically

🔹 For Loop

The for loop is the most common type of loop. It repeats a block of code as long as a condition evaluates to true. The for loop has three parts:

  • Initialization: Sets up the counter variable.
  • Condition: Checked before every iteration; loop stops if false.
  • Increment/Decrement: Updates the counter after each iteration.
JavaScript Editor

🔸 While & Do...While Loop

while loops check the condition before execution, whereas do...while executes at least once.

JavaScript Editor

📐 For...of Loop

The for...of loop iterates over iterable objects like arrays, strings, maps, and sets. It is simple and clean.

JavaScript Editor

📌 For...in Loop

The for...in loop iterates over the keys (property names) of an object.

JavaScript Editor

⚡ Special Keywords: break & continue

JavaScript provides break and continue to control loop execution.

  • break: Exits the loop immediately.
  • continue: Skips the current iteration and continues with the next.

🔹 Nested Loops

Loops can be nested inside another loop. Useful for multi-dimensional data like tables.

JavaScript Editor

⚡ Break & Continue

break exits the loop early. continue skips the current iteration.

JavaScript Editor

🎮 Practice: Student Grades System

Create a small system that iterates over students, filters high scorers, and counts passes.

JavaScript Editor
💡 Challenges:
  • Add average score calculation
  • Highlight students who failed
  • Sort students by score using loops

📚 Summary

  • Loops allow repeated execution of code blocks.
  • for, while, do...while, for...of, for...in are commonly used loops.
  • Use break to exit a loop, continue to skip an iteration.
  • Nested loops are useful but can affect performance.