JavaScript For Loop

For Loop Basics

The for loop is one of the most fundamental and commonly used looping constructs in JavaScript. It allows you to execute a block of code repeatedly for a specific number of iterations, with precise control over the initialization, condition, and increment/decrement.

javascript
1// Basic for loop syntax
2for (let i = 0; i < 5; i++) {
3    console.log("Count: " + i);
4}
5// Output: Count: 0, Count: 1, Count: 2, Count: 3, Count: 4
6
7// Execution flow breakdown:
8// 1. Initialization: let i = 0 (executes once at start)
9// 2. Condition check: i < 5 (checked before each iteration)
10// 3. Code execution: console.log("Count: " + i)
11// 4. Increment: i++ (executes after each iteration)
12// 5. Repeat steps 2-4 until condition becomes false
13
14// More examples:
15for (let count = 1; count <= 3; count++) {
16    console.log("Iteration: " + count);
17}
18// Output: Iteration: 1, Iteration: 2, Iteration: 3
19
20for (let num = 10; num > 5; num--) {
21    console.log("Number: " + num);
22}
23// Output: Number: 10, Number: 9, Number: 8, Number: 7, Number: 6

For Loop Core Components

  • Initialization - Executes once at start, typically used to initialize counter variable
  • Condition - Checked before each iteration, loop continues while true
  • Increment/Decrement - Executes after each iteration, updates counter variable
  • Code Block - Executes repeatedly while condition remains true

For Loop Syntax and Structure

Understanding the complete syntax and structure of for loops is crucial for writing effective iteration logic. The for statement consists of three optional expressions enclosed in parentheses, followed by the code block to execute.

javascript
1// Complete for loop syntax breakdown
2
3// 1. Standard for loop
4for (let i = 0; i < 5; i++) {
5    console.log("Standard: " + i);
6}
7
8// 2. Different increment patterns
9for (let i = 0; i < 10; i += 2) {
10    console.log("Even steps: " + i);
11}
12// Output: Even steps: 0, 2, 4, 6, 8
13
14// 3. Decrementing loop
15for (let i = 5; i > 0; i--) {
16    console.log("Countdown: " + i);
17}
18// Output: Countdown: 5, 4, 3, 2, 1
19
20// 4. Multiple variables in initialization
21for (let i = 0, j = 10; i < 5; i++, j--) {
22    console.log(`i: ${i}, j: ${j}`);
23}
24// Output: i: 0, j: 10; i: 1, j: 9; i: 2, j: 8; i: 3, j: 7; i: 4, j: 6
25
26// 5. Complex conditions
27for (let i = 1; i <= 20 && i !== 13; i++) {
28    console.log("Skip 13: " + i);
29}
30// Stops before 13 due to condition
31
32// 6. Using variables in conditions
33const maxCount = 3;
34for (let i = 0; i < maxCount; i++) {
35    console.log("Variable limit: " + i);
36}
37// Output: Variable limit: 0, 1, 2
38
39// 7. Step by different amounts
40for (let i = 0; i < 100; i += 10) {
41    console.log("Tens: " + i);
42}
43// Output: Tens: 0, 10, 20, 30, 40, 50, 60, 70, 80, 90
44
45// 8. Floating point increments (use with caution)
46for (let i = 0; i < 1; i += 0.2) {
47    console.log("Float: " + i.toFixed(1));
48}
49// Output: Float: 0.0, Float: 0.2, Float: 0.4, Float: 0.6, Float: 0.8
50
51// Syntax rules:
52// - Three expressions in parentheses: initialization; condition; increment
53// - All expressions are optional
54// - Semicolons are required even if expressions are omitted
55// - Code block in curly braces {}
56// - Variables declared in initialization are loop-scoped

For Loop Syntax Components

  • Initialization Expression - let i = 0 - runs once, typically declares counter variable
  • Condition Expression - i < 5 - evaluated before each iteration, loop continues if true
  • Increment Expression - i++ - runs after each iteration, updates counter
  • Loop Body - Code block {} that executes repeatedly

Common For Loop Patterns and Use Cases

For loops are used in various patterns for different scenarios including array iteration, string processing, mathematical sequences, and data transformation.

javascript
1// Pattern 1: Array iteration
2let fruits = ["apple", "banana", "orange", "grape"];
3
4for (let i = 0; i < fruits.length; i++) {
5    console.log(`Fruit ${i + 1}: ${fruits[i]}`);
6}
7// Output: Fruit 1: apple, Fruit 2: banana, Fruit 3: orange, Fruit 4: grape
8
9// Pattern 2: String character iteration
10let message = "Hello";
11
12for (let i = 0; i < message.length; i++) {
13    console.log(`Character ${i}: '${message[i]}'`);
14}
15// Output: Character 0: 'H', Character 1: 'e', Character 2: 'l', Character 3: 'l', Character 4: 'o'
16
17// Pattern 3: Mathematical sequences
18console.log("First 5 square numbers:");
19for (let i = 1; i <= 5; i++) {
20    console.log(`${i}² = ${i * i}`);
21}
22// Output: 1² = 1, 2² = 4, 3² = 9, 4² = 16, 5² = 25
23
24// Pattern 4: Building arrays
25let squares = [];
26for (let i = 1; i <= 5; i++) {
27    squares.push(i * i);
28}
29console.log("Squares array:", squares); // Output: [1, 4, 9, 16, 25]
30
31// Pattern 5: Nested loops for 2D structures
32console.log("Multiplication table (1-3):");
33for (let i = 1; i <= 3; i++) {
34    let row = "";
35    for (let j = 1; j <= 3; j++) {
36        row += `${i * j}\t`; // Tab separated
37    }
38    console.log(row);
39}
40// Output: 1   2   3
41//         2   4   6  
42//         3   6   9
43
44// Pattern 6: Conditional processing within loops
45let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
46let evenNumbers = [];
47let oddNumbers = [];
48
49for (let i = 0; i < numbers.length; i++) {
50    if (numbers[i] % 2 === 0) {
51        evenNumbers.push(numbers[i]);
52    } else {
53        oddNumbers.push(numbers[i]);
54    }
55}
56
57console.log("Even numbers:", evenNumbers); // [2, 4, 6, 8, 10]
58console.log("Odd numbers:", oddNumbers);   // [1, 3, 5, 7, 9]
59
60// Pattern 7: Loop with break statement
61console.log("Numbers until 5:");
62for (let i = 1; i <= 10; i++) {
63    if (i > 5) {
64        break; // Exit loop early
65    }
66    console.log(i);
67}
68// Output: 1, 2, 3, 4, 5
69
70// Pattern 8: Loop with continue statement
71console.log("Odd numbers only:");
72for (let i = 1; i <= 5; i++) {
73    if (i % 2 === 0) {
74        continue; // Skip even numbers
75    }
76    console.log(i);
77}
78// Output: 1, 3, 5
79
80// Pattern 9: Reverse array iteration
81let colors = ["red", "green", "blue", "yellow"];
82
83console.log("Colors in reverse:");
84for (let i = colors.length - 1; i >= 0; i--) {
85    console.log(colors[i]);
86}
87// Output: yellow, blue, green, red
88
89// Pattern 10: Sum calculation
90let prices = [10, 20, 30, 40, 50];
91let total = 0;
92
93for (let i = 0; i < prices.length; i++) {
94    total += prices[i];
95}
96
97console.log(`Total price: $${total}`); // Output: Total price: $150

Loop Control Statements: Break and Continue

The break and continue statements provide fine-grained control over loop execution. Break exits the loop entirely, while continue skips the current iteration and moves to the next one.

javascript
1// Break statement - exiting loops early
2console.log("=== BREAK STATEMENT EXAMPLES ===");
3
4// Example 1: Break when condition met
5for (let i = 1; i <= 10; i++) {
6    if (i === 6) {
7        console.log("Found 6, breaking loop!");
8        break;
9    }
10    console.log("Current number:", i);
11}
12// Output: 1, 2, 3, 4, 5, "Found 6, breaking loop!"
13
14// Example 2: Break in search operations
15let users = ["Alice", "Bob", "Charlie", "David"];
16let searchName = "Charlie";
17let found = false;
18
19for (let i = 0; i < users.length; i++) {
20    if (users[i] === searchName) {
21        found = true;
22        console.log(`Found ${searchName} at index ${i}`);
23        break; // Stop searching once found
24    }
25}
26
27if (!found) {
28    console.log(`${searchName} not found`);
29}
30
31// Example 3: Break in nested loops
32console.log("\nNested loop with break:");
33outerLoop: for (let i = 1; i <= 3; i++) {
34    for (let j = 1; j <= 3; j++) {
35        if (i === 2 && j === 2) {
36            console.log("Breaking both loops at i=2, j=2");
37            break outerLoop; // Break outer loop with label
38        }
39        console.log(`i=${i}, j=${j}`);
40    }
41}
42
43// Continue statement - skipping iterations
44console.log("\n=== CONTINUE STATEMENT EXAMPLES ===");
45
46// Example 1: Skip even numbers
47for (let i = 1; i <= 5; i++) {
48    if (i % 2 === 0) {
49        continue; // Skip even numbers
50    }
51    console.log("Odd number:", i);
52}
53// Output: 1, 3, 5
54
55// Example 2: Skip specific values
56let scores = [85, 92, 78, 45, 95, 32, 88];
57let passingScores = [];
58
59for (let i = 0; i < scores.length; i++) {
60    if (scores[i] < 50) {
61        console.log(`Skipping failing score: ${scores[i]}`);
62        continue; // Skip failing scores
63    }
64    passingScores.push(scores[i]);
65}
66
67console.log("Passing scores:", passingScores); // [85, 92, 78, 95, 88]
68
69// Example 3: Continue with complex conditions
70console.log("\nNumbers divisible by 2 or 3:");
71for (let i = 1; i <= 10; i++) {
72    if (i % 2 !== 0 && i % 3 !== 0) {
73        continue; // Skip numbers not divisible by 2 or 3
74    }
75    console.log(`${i} is divisible by 2 or 3`);
76}
77
78// Example 4: Continue in data processing
79let data = [10, null, 20, undefined, 30, 0, 40];
80let validData = [];
81
82for (let i = 0; i < data.length; i++) {
83    // Skip null, undefined, and 0 values
84    if (data[i] === null || data[i] === undefined || data[i] === 0) {
85        continue;
86    }
87    validData.push(data[i]);
88}
89
90console.log("Valid data:", validData); // [10, 20, 30, 40]
91
92// Practical use case: Data validation and processing
93let userInputs = ["", "hello", "123", "", "world", null, "456"];
94let processedInputs = [];
95
96for (let i = 0; i < userInputs.length; i++) {
97    // Skip empty, null, or undefined inputs
98    if (!userInputs[i]) {
99        console.log(`Skipping invalid input at index ${i}`);
100        continue;
101    }
102    
103    // Process valid inputs
104    let processed = userInputs[i].trim().toUpperCase();
105    processedInputs.push(processed);
106}
107
108console.log("Processed inputs:", processedInputs); // ["HELLO", "123", "WORLD", "456"]

For Loop Variations and Advanced Patterns

Beyond the standard for loop, JavaScript supports several variations and advanced patterns that provide more flexibility for specific use cases.

javascript
1// Variation 1: Omitting initialization (if variable already exists)
2let k = 0;
3for (; k < 3; k++) {
4    console.log("Pre-initialized:", k);
5}
6// Output: 0, 1, 2
7
8// Variation 2: Omitting increment (manual increment inside loop)
9for (let i = 0; i < 3;) {
10    console.log("Manual increment:", i);
11    i++; // Increment inside loop body
12}
13// Output: 0, 1, 2
14
15// Variation 3: Infinite loop with break condition
16let counter = 0;
17for (;;) { // No initialization, condition, or increment
18    console.log("Infinite loop iteration:", counter);
19    counter++;
20    if (counter >= 3) {
21        break; // Must have break to avoid actual infinite loop
22    }
23}
24// Output: 0, 1, 2
25
26// Variation 4: Multiple variables in increment
27for (let a = 0, b = 10; a < 5; a++, b--) {
28    console.log(`a=${a}, b=${b}, sum=${a + b}`);
29}
30// Output: a=0, b=10, sum=10; a=1, b=9, sum=10; etc.
31
32// Variation 5: Complex increment expressions
33for (let i = 1; i <= 16; i *= 2) {
34    console.log("Powers of 2:", i);
35}
36// Output: 1, 2, 4, 8, 16
37
38// Variation 6: Loop with function calls in condition
39function getLimit() {
40    return 3;
41}
42
43for (let i = 0; i < getLimit(); i++) {
44    console.log("Dynamic limit:", i);
45}
46// Output: 0, 1, 2
47
48// Advanced Pattern 1: Caching array length for performance
49let bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
50
51// Good practice: cache length for large arrays
52for (let i = 0, len = bigArray.length; i < len; i++) {
53    console.log(bigArray[i]);
54}
55
56// Advanced Pattern 2: Loop with early returns in functions
57function findFirstEven(numbers) {
58    for (let i = 0; i < numbers.length; i++) {
59        if (numbers[i] % 2 === 0) {
60            return numbers[i]; // Early return
61        }
62    }
63    return null; // No even numbers found
64}
65
66console.log("First even:", findFirstEven([1, 3, 5, 2, 7])); // 2
67
68// Advanced Pattern 3: Loop with error handling
69try {
70    for (let i = 0; i < 5; i++) {
71        if (i === 3) {
72            throw new Error("Something went wrong at iteration 3");
73        }
74        console.log("Safe iteration:", i);
75    }
76} catch (error) {
77    console.error("Loop error:", error.message);
78}
79// Output: 0, 1, 2, "Loop error: Something went wrong at iteration 3"
80
81// Advanced Pattern 4: Loop with timeout (be careful with this!)
82console.log("Delayed iterations:");
83for (let i = 0; i < 3; i++) {
84    setTimeout(() => {
85        console.log("Delayed:", i);
86    }, i * 1000);
87}
88// Output: Delayed: 0 (after 0s), Delayed: 1 (after 1s), Delayed: 2 (after 2s)
89
90// Advanced Pattern 5: Loop with accumulator pattern
91let numbers2 = [1, 2, 3, 4, 5];
92let product = 1;
93
94for (let i = 0; i < numbers2.length; i++) {
95    product *= numbers2[i];
96}
97
98console.log("Product of all numbers:", product); // 120
99
100// Advanced Pattern 6: Loop with transformation
101let names = ["alice", "bob", "charlie"];
102let capitalizedNames = [];
103
104for (let i = 0; i < names.length; i++) {
105    let capitalized = names[i].charAt(0).toUpperCase() + names[i].slice(1);
106    capitalizedNames.push(capitalized);
107}
108
109console.log("Capitalized names:", capitalizedNames); // ["Alice", "Bob", "Charlie"]
110
111// Advanced Pattern 7: Loop with conditional accumulation
112let mixedData = [1, "hello", 2, "world", 3, true, 4];
113let numberSum = 0;
114let stringCount = 0;
115
116for (let i = 0; i < mixedData.length; i++) {
117    if (typeof mixedData[i] === 'number') {
118        numberSum += mixedData[i];
119    } else if (typeof mixedData[i] === 'string') {
120        stringCount++;
121    }
122}
123
124console.log(`Number sum: ${numberSum}, String count: ${stringCount}`); // Number sum: 10, String count: 2

Common For Loop Mistakes and Pitfalls

Understanding common mistakes with for loops helps you write more robust and bug-free code. These pitfalls often lead to infinite loops, off-by-one errors, and unexpected behavior.

javascript
1// Mistake 1: Off-by-one errors
2let arr = ["a", "b", "c"];
3
4// WRONG: Trying to access arr[3] which doesn't exist
5for (let i = 0; i <= arr.length; i++) {
6    // console.log(arr[i]); // arr[3] is undefined
7}
8
9// CORRECT: Use < instead of <=
10for (let i = 0; i < arr.length; i++) {
11    console.log(arr[i]); // a, b, c
12}
13
14// Mistake 2: Modifying loop counter unexpectedly
15// WRONG: Modifying i inside loop can cause unexpected behavior
16for (let i = 0; i < 5; i++) {
17    console.log(i);
18    // i++; // This would cause skipping iterations
19}
20
21// CORRECT: Be careful with loop counter modifications
22for (let i = 0; i < 5; i++) {
23    console.log(i);
24    // Don't modify i unless you have a specific reason
25}
26
27// Mistake 3: Infinite loops
28// WRONG: Forgetting increment or having always-true condition
29// for (let i = 0; i < 5;) { // Missing i++ - infinite loop!
30//     console.log("This will run forever");
31// }
32
33// CORRECT: Always ensure loop has exit condition
34for (let i = 0; i < 5; i++) {
35    console.log("Safe iteration:", i);
36}
37
38// Mistake 4: Variable scope issues
39// WRONG: Using var instead of let (function scope vs block scope)
40for (var j = 0; j < 3; j++) {
41    setTimeout(() => {
42        // console.log("var j:", j); // Always prints 3 due to function scope
43    }, 100);
44}
45
46// CORRECT: Use let for block scope
47for (let k = 0; k < 3; k++) {
48    setTimeout(() => {
49        console.log("let k:", k); // Prints 0, 1, 2 correctly
50    }, 100);
51}
52
53// Mistake 5: Modifying array while iterating
54let items = [1, 2, 3, 4, 5];
55
56// WRONG: Modifying array length during iteration
57// for (let i = 0; i < items.length; i++) {
58//     if (items[i] % 2 === 0) {
59//         items.splice(i, 1); // Changes array length, can skip elements
60//     }
61// }
62
63// CORRECT: Iterate backwards or use while loop
64for (let i = items.length - 1; i >= 0; i--) {
65    if (items[i] % 2 === 0) {
66        items.splice(i, 1);
67    }
68}
69console.log("Items after removal:", items); // [1, 3, 5]
70
71// Mistake 6: Using floating point numbers as counters
72// WRONG: Floating point precision issues
73// for (let i = 0; i < 1; i += 0.1) {
74//     console.log(i); // Might not reach exactly 1 due to floating point precision
75// }
76
77// CORRECT: Use integers or handle precision
78for (let i = 0; i < 10; i++) {
79    console.log(i / 10); // 0, 0.1, 0.2, ..., 0.9
80}
81
82// Mistake 7: Not caching array length for large arrays
83let largeArray = new Array(1000000).fill(0);
84
85// LESS EFFICIENT: length is checked every iteration
86// for (let i = 0; i < largeArray.length; i++) {
87//     // operation
88// }
89
90// MORE EFFICIENT: cache length
91for (let i = 0, len = largeArray.length; i < len; i++) {
92    // operation
93}
94
95// Mistake 8: Using the wrong comparison operator
96// WRONG: Using assignment instead of comparison
97let x = 5;
98// for (let i = 0; i = x; i++) { // = instead of < - infinite loop!
99//     console.log(i);
100// }
101
102// CORRECT: Use proper comparison operator
103for (let i = 0; i < x; i++) {
104    console.log(i);
105}
106
107// Mistake 9: Not handling empty or null arrays
108let possibleArray = null;
109
110// WRONG: Could throw error if array is null
111// for (let i = 0; i < possibleArray.length; i++) {
112//     console.log(possibleArray[i]);
113// }
114
115// CORRECT: Check for null/undefined first
116if (possibleArray) {
117    for (let i = 0; i < possibleArray.length; i++) {
118        console.log(possibleArray[i]);
119    }
120}
121
122// Mistake 10: Complex conditions that are hard to read
123// WRONG: Overly complex condition
124// for (let i = 0; i < arr.length && i !== forbiddenIndex && arr[i] !== null; i++) {
125//     // Hard to understand
126// }
127
128// CORRECT: Break complex conditions or use continue
129for (let i = 0; i < arr.length; i++) {
130    if (i === forbiddenIndex || arr[i] === null) {
131        continue;
132    }
133    // Main logic here
134}

For Loop Best Practices

Following established best practices for for loops leads to more readable, maintainable, and efficient code. These guidelines help you write clean and effective iteration logic.

javascript
1// Best Practice 1: Use descriptive variable names
2let students = ["Alice", "Bob", "Charlie"];
3
4// GOOD - descriptive index variable
5for (let studentIndex = 0; studentIndex < students.length; studentIndex++) {
6    console.log(`Student ${studentIndex + 1}: ${students[studentIndex]}`);
7}
8
9// AVOID - single letter without context
10// for (let i = 0; i < students.length; i++) {
11//     console.log(students[i]);
12// }
13
14// Best Practice 2: Cache array length for large arrays
15let largeDataset = new Array(10000).fill("data");
16
17// GOOD - cached length for performance
18for (let i = 0, dataLength = largeDataset.length; i < dataLength; i++) {
19    // Process data
20}
21
22// Best Practice 3: Use const when counter shouldn't change
23const MAX_ITERATIONS = 10;
24
25// GOOD - const for values that don't change
26for (let i = 0; i < MAX_ITERATIONS; i++) {
27    console.log("Iteration:", i);
28}
29
30// Best Practice 4: Prefer let over var for loop counters
31// GOOD - block scope with let
32for (let counter = 0; counter < 3; counter++) {
33    setTimeout(() => console.log(counter), 100); // 0, 1, 2
34}
35
36// BAD - function scope with var
37// for (var counter = 0; counter < 3; counter++) {
38//     setTimeout(() => console.log(counter), 100); // 3, 3, 3
39// }
40
41// Best Practice 5: Keep loop bodies focused and simple
42let numbers = [1, 2, 3, 4, 5];
43
44// GOOD - extract complex logic to functions
45function processNumber(num) {
46    return num * num + 10;
47}
48
49for (let i = 0; i < numbers.length; i++) {
50    let result = processNumber(numbers[i]);
51    console.log(`Result for ${numbers[i]}: ${result}`);
52}
53
54// Best Practice 6: Use appropriate loop patterns
55// For simple iteration over arrays
56for (let i = 0; i < numbers.length; i++) {
57    console.log(numbers[i]);
58}
59
60// For reverse iteration
61for (let i = numbers.length - 1; i >= 0; i--) {
62    console.log(numbers[i]);
63}
64
65// For steps other than 1
66for (let i = 0; i < numbers.length; i += 2) {
67    console.log("Every other:", numbers[i]);
68}
69
70// Best Practice 7: Handle edge cases gracefully
71let possibleArray = []; // Could be empty
72
73// GOOD - check for empty arrays
74if (possibleArray && possibleArray.length > 0) {
75    for (let i = 0; i < possibleArray.length; i++) {
76        console.log(possibleArray[i]);
77    }
78} else {
79    console.log("Array is empty or null");
80}
81
82// Best Practice 8: Use break and continue appropriately
83let data = [1, 2, 3, -1, 4, 5];
84
85// GOOD - break for early termination
86for (let i = 0; i < data.length; i++) {
87    if (data[i] < 0) {
88        console.log("Negative number found, stopping");
89        break;
90    }
91    console.log("Processing:", data[i]);
92}
93
94// GOOD - continue for skipping elements
95for (let i = 0; i < data.length; i++) {
96    if (data[i] % 2 === 0) {
97        continue; // Skip even numbers
98    }
99    console.log("Odd number:", data[i]);
100}
101
102// Best Practice 9: Consider alternative loops when appropriate
103// Use for...of for simple array iteration (if supported)
104// Use while loops when termination condition is complex
105// Use forEach for functional programming style
106
107// Best Practice 10: Document complex loop logic
108// Process user data with specific conditions
109for (let i = 0; i < data.length; i++) {
110    // Skip invalid entries (null, undefined, empty)
111    if (!data[i]) continue;
112    
113    // Only process numbers greater than threshold
114    if (data[i] > 10) {
115        console.log("Processing large number:", data[i]);
116    }
117}
118
119// Best Practice 11: Avoid modifying the loop counter unnecessarily
120// GOOD - predictable counter behavior
121for (let i = 0; i < 5; i++) {
122    console.log(i); // Always 0,1,2,3,4
123}
124
125// AVOID - unpredictable counter changes
126// for (let i = 0; i < 5; i++) {
127//     console.log(i);
128//     i++; // This would cause 0,2,4 - confusing!
129// }
130
131// Best Practice 12: Use consistent formatting
132// GOOD - consistent spacing and structure
133for (let index = 0; index < items.length; index++) {
134    processItem(items[index]);
135}
136
137// Best Practice 13: Consider performance for large datasets
138let hugeArray = new Array(1000000);
139
140// GOOD - minimize operations inside loop
141const arrayLength = hugeArray.length;
142for (let i = 0; i < arrayLength; i++) {
143    // Fast, minimal operations here
144    hugeArray[i] = i * 2;
145}

JavaScript For Loop FAQ

What is the basic syntax of a for loop?

The basic syntax is: for (initialization; condition; increment) { code }. Initialization runs once at start, condition is checked before each iteration, and increment runs after each iteration. The loop continues as long as the condition is true.

What's the difference between i++ and ++i in for loops?

i++ (post-increment) returns the value then increments, while ++i (pre-increment) increments then returns the value. In for loops, both work the same because the increment happens after the loop body execution. Conventionally, i++ is more commonly used.

Can I use multiple variables in a for loop?

Yes, you can initialize multiple variables separated by commas: for (let i = 0, j = 10; i < 5; i++, j--). You can also have multiple increment expressions separated by commas.

What happens if I omit the initialization, condition, or increment?

All three expressions are optional. If you omit initialization, it runs before the loop. If you omit condition, it defaults to true (infinite loop). If you omit increment, you must handle incrementing inside the loop body to avoid infinite loops.

What's the difference between break and continue?

Break exits the entire loop immediately. Continue skips the current iteration and moves to the next one. Break stops the loop completely, while continue only stops the current iteration.

Why should I use let instead of var for loop counters?

let has block scope, meaning the counter variable is only accessible within the loop. var has function scope, which can lead to unexpected behavior, especially with asynchronous code inside loops. Always use let for loop counters.

How do I loop through an array backwards?

Start from the last index and decrement: for (let i = array.length - 1; i >= 0; i--). This allows you to process array elements from the end to the beginning.

What's an infinite loop and how can I avoid it?

An infinite loop runs forever because the condition never becomes false. Avoid by ensuring the condition will eventually become false, typically by properly incrementing the counter and having a clear termination condition.

When should I use a for loop vs other loop types?

Use for loops when you know how many iterations you need, when you need precise control over the counter, or when iterating with specific patterns. Use while loops when the termination condition is complex, and for...of for simple array iteration.

What are some common for loop performance optimizations?

Cache array length for large arrays, minimize operations inside the loop, avoid function calls in conditions when possible, use appropriate data structures, and consider breaking early when the goal is achieved.