Back
LearnJavaScript From ZeroHow to repeat work without repeating yourself

How to repeat work without repeating yourself

1 min read

Computers love boring, repetitive work

Suppose I ask you to write "I will practice daily" a hundred times. Painful, right? But a computer? It does that happily, in a blink. The tool for repeating work is called a loop.

The for loop

The most common one is the for loop:

for (let i = 1; i <= 5; i++) {
  console.log("Line number " + i);
}

This prints 5 lines. Let me decode the three parts inside ( ), separated by ;:

  1. let i = 1start: begin counting at 1.
  2. i <= 5condition: keep going while i is 5 or less.
  3. i++step: after each round, add 1 to i.

So i becomes 1, 2, 3, 4, 5 — five rounds — then stops. (i++ is just a short way of writing "i = i + 1".)

Why is this such a big deal?

Because real apps deal with lists. A hundred products, fifty messages, a thousand users. You cannot write code for each one by hand. A loop lets you say "do this for every single item" in just a few lines.

let friends = ["Riya", "Sam", "Neha"];

for (let i = 0; i < friends.length; i++) {
  console.log("Hello " + friends[i]);
}

This greets every friend, whether the list has 3 names or 3000. Notice we start at i = 0 — because in JavaScript, lists start counting from 0, not 1. So friends[0] is "Riya". (This trips up everyone at first. It is completely normal.)

A simpler way for lists

JavaScript also gives you for...of, which reads more easily:

for (let friend of friends) {
  console.log("Hello " + friend);
}

Same result, less to think about. Use this when you just want each item, one by one.

Big idea: a loop means "do this again and again until the job is done." It is how a few lines of code can handle millions of items.

🎉 You have now learned the real foundation of JavaScript — printing, variables, types, decisions and loops. Everything else you study from here simply builds on these five ideas.

Tip