HAKATEMIA
11JavaScript

For loops - Repeating an action X times

Easy10MIN

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.

JAVASCRIPT
1let 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.

JAVASCRIPT
1counter <= 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").

JAVASCRIPT
1counter = counter + 1;

Protip: Shorthands for incrementing a counter

This code:

JAVASCRIPT
1counter = counter + 1;

Can be expressed with the shorthand:

JAVASCRIPT
1counter++;

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

JAVASCRIPT
1counter = counter + 5;

There is another shorthand for that!

JAVASCRIPT
1counter += 5;

The same shorthands work for subtraction by the way.

JAVASCRIPT
1counter--;
2counter -= 5;

Example

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

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

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:

JAVASCRIPT
1let total = 0;
2for (let i = 1; i <= 5; i++) {
3  total = total + i;
4}
5console.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

1 / 2
Hakatemia Pro

Learn to hack — start here

Hundreds of interactive courses, virtual labs and CTF challenges in your browser. Start a free trial — no card required.