JavaScript for Loop
Subject: JavaScript
The for loop is one of the most frequently used loops in JavaScript. It allows you to run a block of code a specific number of times. This makes it ideal for scenarios like iterating over arrays, generating numeric sequences, or automating repetitive tasks.
Syntax
Components:
- Initialization: Runs once before the loop begins. Often used to define a counter variable.
- Condition: Checked before every loop iteration. If false, the loop ends.
- Increment/Decrement: Updates the loop counter after each iteration.
Example 1: Basic for Loop
Example 2: Looping Through an Array
Example 3: Decrementing Loop
Example 4: Skipping Values Using continue
Example 5: Stopping Loop Using break
When to Use for Loop
- When you know the exact number of iterations needed.
- When working with array indices.
- When you need full control over the loop’s start, stop, and step values.
Key Takeaways
- The
forloop is best for fixed-count iterations. - It consists of initialization, condition, and increment expressions.
continueskips the current iteration.breakexits the loop entirely.- Always ensure your loop condition will eventually become false to avoid infinite loops.