#10 - JavaScript For Loop
#10 - JavaScript For Loop
programiz.com/javascript/for-loop
This tutorial focuses on JavaScript for loop. You will learn about the other type of loops in
the upcoming tutorials.
Here,
1. The initialExpression initializes and/or declares variables and executes only once.
2. The condition is evaluated.
If the condition is false, the for loop is terminated.
If the condition is true, the block of code inside of the for loop is executed.
3. The updateExpression updates the value of initialExpression when the condition
is true.
4. The condition is evaluated again. This process continues until the condition is
false.
To learn more about the conditions, visit JavaScript Comparison and Logical Operators.
1/5
Flowchart of JavaScript for loop
// looping from i = 1 to 5
for (let i = 1; i <= n; i++) {
console.log(`I love JavaScript.`);
}
Output
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
2/5
Iteration Variable Condition: i <= n Action
// looping from i = 1 to 5
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
console.log(i); // printing the value of i
}
Output
1
2
3
4
5
3/5
4th i = 4 true 4 is printed.
n = 5 i is increased to 5.
// looping from i = 1 to n
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
sum += i; // sum = sum + i
}
console.log('sum:', sum);
Output
sum: 5050
Here, the value of sum is 0 initially. Then, a for loop is iterated from i = 1 to 100. In
each iteration, i is added to sum and its value is increased by 1.
When i becomes 101, the test condition is false and sum will be equal to 0 + 1 + 2 +
... + 100.
The above program to add sum of natural numbers can also be written as
// looping from i = n to 1
// in each iteration, i is decreased by 1
for(let i = n; i >= 1; i-- ) {
// adding i to sum in each iteration
sum += i; // sum = sum + i
}
console.log('sum:',sum);
This program also gives the same output as the Example 3. You can accomplish the
same task in many different ways in programming; programming is all about logic.
4/5
Although both ways are correct, you should try to make your code more readable.
In the above program, the condition is always true which will then run the code for infinite
times.
In the next tutorial, you will learn about while and do...while loop.
5/5