Home
Node.js
for Loop Examples
Updated Aug 14, 2025
Dot Net Perls

For

With a for-loop, we have an efficient and standard looping construct. Within Node.js, the V8 engine optimizes for-loops—this makes them an effective and fast construct.

And with a while-loop, we can do the same thing as a for-loop, but the syntax may be simpler when an endpoint is not known. Thus while-true is a good infinite loop.

For example

The program begins at 0 and stops at 4. When the loop var "i" reaches 5, the for-loop is terminated before being run again.

// Loop over first 5 numbers and print them.
for (var i = 0; i < 5; i++) {
    console.log("FOR-LOOP ITERATION: " + i);
}
FOR-LOOP ITERATION: 0 FOR-LOOP ITERATION: 1 FOR-LOOP ITERATION: 2 FOR-LOOP ITERATION: 3 FOR-LOOP ITERATION: 4

While

Here we rewrite the first for-loop into a while-loop. This version of the looping logic is somewhat harder to follow for both people and compilers.

So We usually prefer the for-loop when the end point is known. But for an infinite loop, the while-loop is preferred.
// Use while-loop over first five numbers.
var i = 0;
while (i < 5) {
    console.log("WHILE INDEX: " + i);
    i++;
}
WHILE INDEX: 0 WHILE INDEX: 1 WHILE INDEX: 2 WHILE INDEX: 3 WHILE INDEX: 4

For-of loop

This loop enumerates the elements in an array. It does not return indexes like for-in. It returns the actual elements in the array.

var numbers = [10, 20, 30];

// Loop over the numbers in the array.
for (var number of numbers) {
    console.log("FOR OF: " + number);
}
FOR OF: 10 FOR OF: 20 FOR OF: 30

For-in loop

This loop returns all the indexes of an array. So in an array of 3 elements, we get the indexes 0, 1 and 2. We can then access the elements themselves.

var numbers = [10, 20, 30];

// Loop over the indexes.
// ... The "i" identifier is a standard index variable name.
for (var i in numbers) {
    console.log("INDEX: " + i);
    console.log("ELEMENT: " + numbers[i]);
}
INDEX: 0 ELEMENT: 10 INDEX: 1 ELEMENT: 20 INDEX: 2 ELEMENT: 30

Array iteration, warning

Hoisting variables and caching the length in a for-loop may lead to micro-benchmark improvements. But these can disappear on more complex, real programs.

Most programs are built around looping. With loop we construct web pages, animate graphics and even decide an optimal chess move.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 14, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen