`for` Loop
Swipe to show menu
A for loop in JavaScript is a fundamental tool for repeating a block of code multiple times. It is especially useful when you want to perform the same action for each item in an array. The basic structure of a for loop includes three main parts inside the parentheses: the initialization, the condition, and the increment.
- The initialization sets up a variable, usually as a counter;
- The condition checks whether the loop should keep running;
- The increment updates the counter after each iteration.
This structure allows you to control exactly how many times the loop runs.
The general syntax looks like this:
for (let i = 0; i < array.length; i++) {
// code to run on each iteration
}
Here, i is a counter that starts at 0. The loop continues as long as i is less than the length of the array. After each iteration, i increases by one.
12345678const numbers = [4, 7, 1, 9, 2]; let sum = 0; for (let i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } console.log("Sum:", sum); // Output: Sum: 23
When working with for loops, you may want to control how and when the loop finishes or skips certain steps. The break statement lets you exit the loop early if a condition is met. The continue statement skips the current iteration and moves on to the next one. These tools are useful for handling specific situations, but using them incorrectly can lead to bugs.
12345678910111213141516const scores = [85, 42, 77, 0, 91, 65]; let validTotal = 0; for (let i = 0; i < scores.length; i++) { if (scores[i] === 0) { // Skip invalid score continue; } if (scores[i] > 90) { // Stop processing if a top score is found break; } validTotal += scores[i]; } console.log("Valid total:", validTotal);
A common pitfall with for loops is using the wrong loop condition or increment, which can cause infinite loops or skip elements. Always make sure your loop counter starts and ends at the correct values, and check that your increment or decrement moves the loop toward its stopping point. Remember, array indexes start at 0 and go up to array.length - 1.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat