Cityscape
Girl

JavaScript

For loops - Repeating an action X times

Easy
10 min

What Is a For Loop?

A for loop is a way to tell your program to repeat an action for an X amount of times. The loop has three main parts: for(Initializaton; Condition; Increment)

Initialization

Set up a variable (often called a counter) to start at a specific value.

let counter = 0;

Condition

Tell the loop how long to continue running (this will be an expression that is evaluated before each iteration, and if it evaluates to true, we go to the loop code).

For example, if we want to do something for 10 times and we started with the counter being 0, we'd want to use an expression as the condition that would evaluate to true as long as the counter is less than 10.

counter <= 10

Increment

Change the counter after each loop cycle. If we wouldn't increment the counter, the condition would forever remain true, and the loop would run indefinitely ("infinite loop").

counter = counter + 1;

Protip: Shorthands for incrementing a counter

This code:

counter = counter + 1;

Can be expressed with the shorthand:

counter++;

They are the same thing! It's a shorthand to make developer's life easier. And what if you want to do this?

counter = counter + 5;

There is another shorthand for that!

counter += 5;

The same shorthands work for subtraction by the way.

counter--;
counter -= 5;

Example

Here’s a basic example that prints numbers 1 to 5:

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

In this code:

  • We start with i equal to 1.
  • The loop runs as long as i is less than or equal to 5.
  • After each cycle, i increases by 1.
  • Each time, the current value of i is printed.

Another example

Loops are also useful for performing calculations repeatedly. For example, you can use a loop to add all numbers from 1 to 5 together. This is done by keeping a running total that is updated with each loop cycle.

Here’s how you might do that:

let total = 0;
for (let i = 1; i <= 5; i++) {
  total = total + i;
}
console.log(total); // Should print 15
  • We create a variable total and start it at 0.
  • For each number from 1 to 5, we add it to total.
  • After the loop finishes, total holds the sum of the numbers 1+2+3+4+5 (which is 15).

Exercises

Print Numbers 1 to 5

Write a for loop that prints each number from 1 to 5 on a separate line.

Calculate the Sum of Numbers 1 to 5

  • Create a variable named total set to 0.
  • Write a for loop that adds each number from 1 to 5 to total.
  • Print total using console.log(total).

hakatemia pro

Ready to become an ethical hacker?
Start today.

As a member of Hakatemia you get unlimited access to Hakatemia modules, exercises and tools, and you get access to the Hakatemia Discord channel where you can ask for help from both instructors and other Hakatemia members.