JavaScript For Loop

For loop code block contains the initialization, conditions and change expression instead of only condition which was previously used in while loop. For loop comes handy as you dont have to remember to add different expressions to make the condition false. Also it save you a few lines of code.

Syntax of For Loop

for (initialization; condition; change-expression){
	statement1;
	statement2;
}

Initialization

It means to intitialise variable with some value, in case of a loop, this is known as a counter. Also, variables initialised in for loop remains in that scope only. This gets executed at the starting.

Condition

This is the conditions that is checked to come out of for loop. With each run, this condition is taken into account and checked. If false, the loop terminates. Basically, its the condition to make the loop going.

Change-expression

The changes to variable is done here. Either increment or decrement condition in applied as per the requirement of the program. When all the statements inside the loop are completed, then this step is executed.

If we take the previous example, then there are many ways to do it via for loop.

for(var i=1;i<=10000;i++){
	console.log(i);
}
var i=1;
for(;i<=10000;i++){
	console.log(i);
}
for(var i=1;i<10000;){
	i++;
	console.log(i);
}

Infinite For Loop

Can you make the loop run without any of these 3 statements?

for(;;){
	Some statements
}

Note – This may lead to infinite loop if not implemented properly

Break the For Loop

var a = 0;
for(;;){
a++;
console.log(a);
if(a===10) 
	break;
}
Translate »