What Are Loops in JavaScript?

Learning Goal

Understand what loops are, why they’re used in programming, and how they help you write cleaner, smarter code.


Concept: Repeating Code Efficiently

In JavaScript (and most programming languages), loops allow you to repeat a block of code multiple times without having to write it again and again.


Without a loop:

Let’s say you want to print “Hello!” 5 times:

console.log("Hello!");
console.log("Hello!");
console.log("Hello!");
console.log("Hello!");
console.log("Hello!");

This works, but it’s:

  • Long
  • Repetitive
  • Hard to update (what if you want 100 lines?)

With a loop:

for (let i = 0; i < 5; i++) {
  console.log("Hello!");
}

This prints “Hello!” 5 times — but the code is:

  • Shorter
  • Easier to read
  • Easy to update (just change 5 to any number)

What Exactly Is a Loop?

A loop is a programming tool that:

  • Starts at a specific value (like 0)
  • Checks a condition (e.g., is i < 5?)
  • Executes a block of code if the condition is true
  • Repeats the process until the condition becomes false

Visual Example:

StepWhat Happens
i = 0Check: Is i < 5? → Yes → Run code
i = 1Check: Is i < 5? → Yes → Run code
i = 2Yes → Run code
i = 3Yes → Run code
i = 4Yes → Run code
i = 5No → Stop the loop

Real-Life Analogy

Doing Push-Ups at the Gym

You want to do 10 push-ups. Instead of:

  • “Do 1 push-up”
  • “Do 1 push-up”

You say:

“Repeat push-up 10 times”

That’s what a loop does in code.


Why Are Loops Useful?

Loops are powerful because they let you:

Use CaseExample
Repeat a taskDisplay a message multiple times
Process a listGo through all items in an array
Automate behaviorAnimate something on a website
Search dataFind a value inside a dataset
Validate inputCheck every field in a form

Simple Loop Example in JavaScript

for (let i = 1; i <= 3; i++) {
  console.log("This is loop number " + i);
}

Output:

This is loop number 1
This is loop number 2
This is loop number 3

Key Takeaways

  • Loops repeat code automatically
  • Save time and make code more efficient
  • Work by setting a start, checking a condition, and repeating until it’s no longer true
  • There are several types of loops (e.g., for, while, do...while) that we’ll explore next