AI Features

The for and for-in loops

In this lesson, you will have an overview of all flow-control statements provided by the JavaScript language.

The for Loop

Just as in many programming languages, the for loop provides a pretest with optional variable initialization and optional post-loop code to be executed:

Illustration

Here is an illustration to explain the above concept

Syntax

The syntax of the for loop in JavaScript is as follows:

for (initialization ; condition ; post_loop_expression) statement

Example

This example shows the usage of a for loop:

Node.js
for (var i = 0; i < 10; i++) {
console.log(i);
}

The initialization, condition, and post_loop_expression are all optional, so you can create an infinite loop by omitting all of them:

for (;;;) {
console.log("Nothing gonna stop me");
}

The for-in loop

There is another for loop in JavaScript that can be used only to enumerate the properties of an object, the for-in ...