In Vibe Coding, we often want to repeat actions, creating a rhythm in our programs. This is where loops and iterations come into play. Think of them as the persistent beat that drives your code forward, executing a block of instructions multiple times. We can visualize these repetitive actions on our Vibe Canvas as a recurring pattern, a flow that circles back to itself until a condition is met.
The most fundamental loop in many programming languages is the 'for' loop. It's perfect for situations where you know exactly how many times you want to repeat an action. On our Vibe Canvas, this might look like a series of steps leading to a decision point that, when the condition is met, gracefully exits the loop. If not, it circles back to perform the steps again.
for (let i = 0; i < 5; i++) {
console.log('Repeating step ' + i);
}graph TD;
A[Start Loop] --> B{Condition: i < 5?};
B -- Yes --> C[Execute Code Block];
C --> D[Increment i];
D --> B;
B -- No --> E[End Loop];
Another powerful tool for repetition is the 'while' loop. Unlike the 'for' loop, the 'while' loop continues as long as a specific condition remains true. This makes it ideal for scenarios where the number of repetitions isn't predetermined, but rather depends on the state of your program. Visually, this is a continuous cycle, a pulsing rhythm that only stops when the environment changes to meet its exit criteria.
let count = 0;
while (count < 3) {
console.log('Still going...');
count++;
}graph TD;
A[Start Loop] --> B{Condition: count < 3?};
B -- Yes --> C[Execute Code Block];
C --> D[Update count];
D --> B;
B -- No --> E[End Loop];
The 'do-while' loop is similar to the 'while' loop, but with a key difference: it always executes the code block at least once before checking the condition. This can be useful when you need to perform an action at least one time, regardless of the initial state. On our canvas, this loop begins with an action, then checks if it needs to repeat.