Search⌘ K
AI Features

The For Loop

Explore how to implement the for loop in JavaScript to simplify iteration. Learn the syntax, how it differs from while loops, and why readability is more important than micro-optimizations. This lesson helps you write cleaner and more efficient loop code.

We'll cover the following...

Introduction

You will now learn another loop that is perfect for iteration: the for loop. This loop combines several lines of code into one. The execution of the ‘for’ loop is identical to the ‘while’ loop:

Node.js
initialization_of_loop_variable;
while ( condition ) {
statements;
increment_loop_variable;
}
for ( initialization_of_loop_variable; condition; increment_loop_variable ) {
statements;
}

The ‘for’ loop has everything you need in one line. You don’t have to mix your loop body with the increment of the loop variable. The execution of the ‘for’ loop is as follows:

  1. initialization_of_loop_variable
  2. check condition. If condition is falsy, exit the ‘for’ loop
...