Loops are programming constructs used to repeat a block of code multiple times until a specific condition is met. The classic for loop is the most versatile and widely used counting loop in JavaScript.
1. Anatomy of the Standard for Loop
A standard for loop consists of three expressions separated by semicolons:
You can place loops inside loops (for example, traversing a 2D matrix or multiplication table):
1for(let i =1; i <=3; i++){
2for(let j =1; j <=3; j++){
3 console.log(`${i} * ${j} = ${i * j}`);
4}
5}
Important Warning
[!WARNING]
Performance Alert: A nested loop with $N$ iterations inside a loop with $N$ iterations runs $N^2$ times ($O(N^2)$ time complexity). Keep nested loops shallow on large datasets!
4. The Infinite Loop Danger
If the condition never evaluates to false, the loop will run forever, consuming 100% CPU and crashing the browser tab:
1// ❌ CRASH DANGER: i will never be less than 0!
2for(let i =0; i >=0; i++){
3// Freezes the browser!
4}
Interactive Quiz• Knowledge Check
Practice Quiz
Question 1
What are the three parts of a standard for loop header separated by semicolons?
Question 2
How many times does the loop for (let i = 0; i < 4; i++) execute?
Question 3
How do you loop through an array items backward from the last element to the first?
Question 4
What happens if the continuation condition in a for loop is omitted (e.g. for (;;) )?
Question 5
Why is let preferred over var when declaring the loop counter i?
Next Lesson
While and Do-While Loops
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.