Search⌘ K
AI Features

The for and for-in loops

Explore how to use for and for-in loops in JavaScript to iterate over arrays and object properties. Understand the use of break and continue statements to manage loop flow and control execution in nested loops. Gain practical examples to enhance your ability to write efficient loops in JavaScript.

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:

Node.js
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:

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