JavaScript Notes
Master the JavaScript for loop with initialization, condition, increment, loop variations, for...in, for...of, nested loops, performance tips, and interview questions with outputs.
What is the For Loop?
The for loop is the most commonly used loop in JavaScript for executing a block of code a specific number of times. It combines initialization, condition checking, and updating in a single line, making it ideal for iterating over arrays, counting operations, and any scenario where you know (or can calculate) how many times the loop should run.
Syntax
for (initialization; condition; update) {
// Code to repeat
}Three parts in parentheses:
- Initialization – runs once before the loop starts (usually declares counter)
- Condition – checked before each iteration; loop continues while
true - Update – runs after each iteration (usually increments/decrements counter)
Execution Flow
Visual Diagram
Basic For Loop Examples
Example 1: Counting 1 to 5
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
Example 2: Counting Down
for (let i = 10; i >= 1; i--) {
console.log(i);
}
console.log("Liftoff! 🚀");10 9 8 7 6 5 4 3 2 1 Liftoff! 🚀
Example 3: Increment by 2 (Even Numbers)
console.log("Even numbers from 2 to 20:");
for (let i = 2; i <= 20; i += 2) {
process.stdout.write(i + " ");
}
console.log("");Even numbers from 2 to 20: 2 4 6 8 10 12 14 16 18 20
Example 4: Sum of Numbers
Sum of 1 to 100: 5050
Iterating Over Arrays
Basic Array Iteration
1. Apple 2. Banana 3. Cherry 4. Date 5. Elderberry
Finding an Element
Found 56 at index 4
Finding Maximum Value
Highest score: 95 at index 4
Iterating Over Strings
Characters in reverse: tpircSavaJ Vowels in "JavaScript": 3
For Loop Variations
Omitting Parts of the For Loop
j = 0 j = 1 j = 2 --- k = 0 k = 2 k = 4 --- m = 0 m = 1 m = 2
Multiple Variables in For Loop
left=0, right=4 left=1, right=3
For...in Loop (Object Properties)
The for...in loop iterates over the enumerable property keys of an object.
name: Alice age: 28 city: Mumbai profession: Developer
For...in with Arrays (Not Recommended)
Type of index: string, value: red Type of index: string, value: green Type of index: string, value: blue
Warning:for...ingives string indices and may include inherited properties. Usefor...ofor regularforloop for arrays.
For...of Loop (Iterable Values)
The for...of loop iterates over values of iterable objects (arrays, strings, maps, sets).
Learning: JavaScript Learning: Python Learning: Go Learning: Rust
For...of with Strings
let greeting = "Hello!";
for (let char of greeting) {
console.log(char);
}H e l l o !
For...of with entries() (Index + Value)
0: laptop 1: phone 2: tablet
Practical Examples
Multiplication Table
Multiplication Table of 7: 7 × 1 = 7 7 × 2 = 14 7 × 3 = 21 7 × 4 = 28 7 × 5 = 35 7 × 6 = 42 7 × 7 = 49 7 × 8 = 56 7 × 9 = 63 7 × 10 = 70
Fibonacci Sequence
First 10 Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Array Filtering
All ages: [14, 22, 18, 30, 12, 25, 17, 19] Adults (>=18): [22, 18, 30, 25, 19] Count: 5
Reverse an Array
Original: [1, 2, 3, 4, 5] Reversed: [5, 4, 3, 2, 1]
Palindrome Check
madam: true hello: false racecar: true JavaScript: false
Performance Tips
Cache Array Length
First 5: [0, 2, 4, 6, 8] Last 5: [1990, 1992, 1994, 1996, 1998]
Prefer let Over var
var after loop: 3 let is properly scoped
❌ Common Mistakes
Mistake 1: Off-by-One Errors
10 20 30 40 50
Mistake 2: Infinite Loop — Wrong Condition Direction
Safe iteration: 0 Safe iteration: 1 Safe iteration: 2 Safe iteration: 3 Safe iteration: 4
Mistake 3: Closure Issue with var in Loops
var result: 3 3 3 let result: 0 1 2
🎤 Interview Questions
Q1. What are the three parts of a for loop? > (1) Initialization — runs once before loop starts, (2) Condition — checked before each iteration; loop runs while true, (3) Update — runs after each iteration. All three are optional (you can omit any with just the semicolons).
Q2. What is the difference between for...in and for...of? > for...in iterates over property keys of an object (returns strings). for...of iterates over values of iterables (arrays, strings, maps, sets). Use for...of for arrays and for...in for object properties.
Q3. Why should you use let instead of var in for loops? > let is block-scoped — the loop variable is contained to the loop block. var is function-scoped — it leaks outside the loop. This also affects closures: with var, all functions created in a loop share the same variable; with let, each iteration has its own copy.
Q4. What is the output when i = 3 triggers continue?
0, 1, 2, 4— continue skips the current iteration (i=3) and jumps toi++, then checksi < 5.
Q5. Can you omit parts of the for loop? > Yes! All three parts are optional: for (;;) creates an infinite loop. Initialize outside, update inside, or use break for condition — all valid patterns.
Q6. What is the time complexity of a nested for loop? > O(n²) for two nested loops both running n times. The inner loop executes n times for each of the n outer iterations, totaling n × n = n² iterations.
Q7. Find the factorial using a for loop.
5! = 120
Q8. What is the closure issue with var in loops? > Variables declared with var are function-scoped and hoisted. In a loop, all closures created share the same var variable. By the time they execute, the variable has the final loop value. Use let to create a new binding per iteration.
🔑 Key Takeaways
| Concept | Detail |
|---|---|
| Best for | Known number of iterations |
| Three parts | Initialization, Condition, Update |
Use let | Block-scoped, no closure issues |
for...of | Iterate values of iterables (arrays, strings) |
for...in | Iterate keys of objects (not recommended for arrays) |
| Off-by-one | Use i < arr.length, NOT i <= arr.length |
| Performance | Cache arr.length in a variable for large loops |
💡 Remember: The for loop is your go-to when you know exactly how many times to repeat something. Master it and you can iterate over any data structure with precision!Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript For Loop Tutorial – Complete Guide with Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, control, flow, for
Related JavaScript Master Course Topics