for Loop in JavaScript

A for loop in JavaScript is the most common type of loop in JavaScript. It is the type of loop that allows you to iterate over a collection of items, such as an array or object.

The syntax of for loop is:

for (initialization, condition, increment/decrement){
    //code
}

where.

Initialization is the first step where you initialize a value for the beginning of the loop. Typically, the start value is 0, but can be changed as per the condition.

Condition is the second step in which when the statement satisfies the condition, the loop ends.

increment/decrement is the final step in which the value gets incremented or decremented by 1 or given value as per the condition.

Let's understand for loop with the help of an example.

Example 1:

for(int i=0;i<5;i++){
    console.log(i);
}
Output 1:

0

1

2

3

4

Inference of the output 1: During each iteration of the loop, we add the value of the loop counter variable to the count variable. After the loop has completed, we output the value of the count variable to the console.

Example 2:

let count = 0;
for (let i = 0; i < 10; i++) {
    count += i;
}
console.log(count);
Output 2:

45

Inference of the output 2: During each iteration of the loop, we add the value of the loop counter variable to the count variable. After the loop has completed, we output the value of the count variable to the console.

Conclusion

In this article, we've discussed about the for loop in JavaScript, its syntax and few examples which describes its meaning. The conclusion is that the for loop is a powerful tool which is used to iterate through the given condition. Let's move ahead and read about other types of loop in next article.


Learn via Video Course

Javascript(English) Logo

Javascript(English)

72966

3 hrs