Ad space (banner)
🟨JavaScript Lessons
Lesson 4 / 69

Loops (for Statements)

In this lesson you'll learn how to write repeating logic with JavaScript's for statement, so you can run the same processing efficiently over and over. This is aimed at people searching "JavaScript for loop syntax" or "JavaScript loop for beginners."

When you want to repeat the same operation many times, you use a loop. A for statement repeats by specifying three parts: for (initial value; condition; update) { ... }. Instead of copy-pasting the same code 100 times, a loop lets you express a huge amount of processing in just a few lines — that's the power of a loop. The loop ends the moment the condition is no longer satisfied.

The sample code starts at let i = 1 and repeats 5 times while i <= 5, increasing i by 1 each time with i++. A for loop is also used very often to process the contents of an array one at a time, and it's the foundation for the array operations you'll learn about later — a genuinely essential piece of syntax.

A common stumbling block is forgetting to write the update part (i++) or getting the condition wrong, which creates an "infinite loop" that never ends. If the browser seems to freeze, check the condition and update parts first. Being off by one in the number of iterations (an "off-by-one error") is another very common mistake.

In real development, for loops show up in a huge range of situations: displaying a list of products from an array one by one on screen, or retrying a network request a fixed number of times. The ability to design what a loop's body actually does is an essential skill in everyday programming.

A for loop is often paired with an array like for (let i = 0; i < fruits.length; i++) — the classic pattern of repeating once per array element. If you tie the loop's stop condition to the array's length, the loop automatically repeats the right number of times even if the number of elements changes.

If you specify the number of repetitions with a variable, you get a more flexible loop like for (let i = 1; i <= count; i++). Once you can write loops whose repeat count changes depending on the situation, rather than a fixed number, the range of things you can build expands enormously.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)