Menu
CoddyTech

For Loop

Part of the Fundamentals section of Coddy's JavaScript journey. Lesson 38 of 77.

Sometimes when programming it's necessary to perform same or almost the same operation a couple of times.

To prevent writing the same thing over and over again we can use Loops.

The for loop has the following syntax

for (let i = start; i < end; i++) {
    code;
}

The let i = start determines the initial value of i, i < end determines the condition for the loop to continue, and i++ increments i after each iteration. The i will receive all values from start to end (not including end) sequentially. For example:

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

It will execute the print statement 5 times:

0
1
2
3
4

Loops have many use cases. For example let's sum all the number from 1 to 100:

let sum_numbers = 0;
for (let i = 1; i <= 100; i++) {
    sum_numbers += i;
}
console.log(sum_numbers);

This will first loop through all numbers between 1 to 100 (including 100) and sum all of them. Then it will print the sum_numbers variable

challenge icon

Challenge

Beginner

Read an integer n (the starter code already does this). Use a for loop to print "Hello Coddy: " and the i value for every number from 3 to n, both included.

For example, if n is 6, the output is:

Hello Coddy: 3
Hello Coddy: 4
Hello Coddy: 5
Hello Coddy: 6

If n is 27, the loop prints 25 lines, from Hello Coddy: 3 to Hello Coddy: 27.

Try it yourself

let n = parseInt(inp); // Don't change this line

// Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online JavaScript compiler