Javascript for Statement

Introduction

The for statement is a pretest loop.

It can do variable initialization before entering the loop and defining post loop code to be executed.

Here's the syntax:

for (initialization; expression; post-loop-expression) statement 

And here's an example of its usage:

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

This code defines a variable i that begins with the value 0.

The for loop is entered only if the conditional expression (i < count) evaluates to true.

It possible that the body of the code might not be executed.

If the body is executed, the post loop expression is also executed, iterating the variable i.

This for loop is the same as the following:

let count = 10; 
let i = 0; 
while (i < count) { 
  console.log(i); 
  i++; 
} 

The initialization, control expression, and post loop expression are all optional.

You can create an infinite loop by omitting all three, like this:

for (;;) {  // infinite loop 
  doSomething(); 
} 

Including only the control expression effectively turns a for loop into a while loop:

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



PreviousNext

Related