vibecodai logovibecodai
← All JavaScript lessons

JavaScript · Lesson 4 · 12 min

Loops — Repeat Yourself

Use for loops to repeat actions without copying the same code.

You will learn

  • Write a basic for loop
  • Use a counter variable
  • Repeat console.log a set number of times

Loops save time. Instead of writing console.log ten times, a loop can do it for you. The for loop is great when you know how many times to repeat.

How a for loop works

for (let i = 0; i < 5; i++) means: start i at 0, keep going while i is less than 5, and add 1 to i after each round. The code inside { } runs each round.

Countdown example

Change the loop to count from 5 down to 1 for a rocket launch countdown!

Try it yourself

Output

Press Run code to see results here.

Tip: Try i <= 10 to count higher, or log i * 2 each time.