Understanding Basic for
Loops in JavaScript
In this video, I walk through how to use basic for
loops in JavaScript. You'll learn the structure of a loop, why it works, and how to use common patterns like incrementing with i++
.
Anatomy of a for
Loop
A for
loop has three main parts inside the parentheses:
- Initialization – where the loop starts
- Condition – the check that determines if the loop should continue
- Increment – what updates the value each time the loop runs
Example:
1for (let i = 0; i < 10; i++) {
2 console.log(i);
3}
let i = 0
initializes the loop.
i < 10
is the condition to keep going.
i++
increments i
by 1 each loop.
Output:
0
1
2
3
4
5
6
7
8
9
Making It Inclusive
To include the number 10 in your output, change the condition:
1for (let i = 0; i <= 10; i++) {
2 console.log(i);
3}
Using i++
vs i = i + 1
1i = i + 1; // Longer form
2i++; // Common shorthand
Both do the same thing—increment i
by 1.
Loop Range Examples
1for (let i = 0; i < 100; i++) {
2 console.log(i);
3}
- Runs 100 times (from 0 to 99).
- If
i = 100
at the start, it never runs.
- If
i = 99
, it runs once and prints 99.
Scope Behavior
Using let
:
1for (let i = 0; i < 10; i++) {
2 // i is only available inside this block
3}
4console.log(i); // Error: i is not defined
Using var
:
1for (var i = 0; i < 10; i++) {
2 // i is available outside the loop
3}
4console.log(i); // Works, logs 10
let
has block scope.
var
has function scope and gets hoisted.
Summary
- A
for
loop is a compact and powerful way to run code repeatedly.
- Use
let
for block-scoped counters.
- Prefer
i++
for incrementing—it’s clear and concise.
- Be mindful of your condition to control how many times the loop runs.
- Use
var
only when you need broader scope, and understand how hoisting works.
Loops are foundational to programming—get comfortable with them, and everything else becomes easier.