TypeScript For Loop
Learn how to repeat code using for loops in TypeScript. Understand initialization, conditions, increment and decrement, nested loops, and practical examples with expected outputs.
What Will We Learn?
For loops help developers process lists, count values, calculate totals, and repeat instructions efficiently.
- Understand the syntax of a for loop.
- Learn initialization, condition, and update.
- Print numbers in ascending and descending order.
- Calculate totals using loops.
- Understand nested for loops.
- Use break and continue inside loops.
- Apply loops in practical student-related examples.
For Loop Workflow
Follow these steps to understand how a for loop works.
Step 1
InitializeCreate the counter variable.
Step 2
Check ConditionCheck whether the loop should run.
Step 3
ExecuteRun the loop body.
Step 4
UpdateUpdate the counter and repeat.
1. For Loop Syntax
A standard for loop contains three parts: initialization, condition, and update.
Syntax
for (initialization; condition; update) {
// Statements to execute
}
Three Parts of a For Loop
| Part | Purpose | Example |
|---|---|---|
| Initialization | Creates or initializes the loop counter. | let i = 1 |
| Condition | Determines whether another iteration should run. | i <= 5 |
| Update | Changes the counter after an iteration. | i++ |
2. Basic For Loop
A for loop can display a sequence of numbers. It starts with an initial value and repeats until the condition becomes false.
Example
for (let i: number = 1; i <= 5; i++) {
console.log(i);
}
Expected Output
1
2
3
4
5
How It Works
- The variable
istarts at 1. - The condition checks whether
i <= 5. - The loop body prints the current value.
i++increases the value by one after each iteration.
3. For Loop in Descending Order
A for loop can also display numbers from a higher value to a lower value by using decrement.
Example
for (let i: number = 5; i >= 1; i--) {
console.log(i);
}
Expected Output
5
4
3
2
1
The counter begins at 5. The i--
expression decreases the counter by one after
every iteration.
4. Calculate the Sum Using a For Loop
A loop can calculate a running total by adding each number to a variable.
Example
let sum: number = 0;
for (let i: number = 1; i <= 5; i++) {
sum += i;
}
console.log("Sum: " + sum);
Expected Output
Sum: 15
Calculation
sum = 0 + 1;
sum = 1 + 2;
sum = 3 + 3;
sum = 6 + 4;
sum = 10 + 5;
// Final sum = 15
The sum variable stores the running total.
After the loop completes, it contains 15.
5. Loop Through an Array
A for loop can access array elements by their index. Array indexes begin at zero.
Example
let students: string[] = ["Rahul", "Priya", "Amit"];
for (let i: number = 0; i < students.length; i++) {
console.log(students[i]);
}
Expected Output
Rahul
Priya
Amit
The loop starts with index 0 and continues while
i is less than
students.length. It displays each
student name once.
6. Print a Multiplication Table
A for loop can generate a multiplication table by multiplying a number by the loop counter.
Example
let number: number = 5;
for (let i: number = 1; i <= 10; i++) {
console.log(number + " x " + i + " = " + (number * i));
}
Expected Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Each iteration multiplies 5 by the current value
of i.
7. Nested For Loop
A nested for loop is a for loop inside another for loop. It is useful for processing rows and columns or generating patterns.
Example
for (let i: number = 1; i <= 3; i++) {
for (let j: number = 1; j <= 2; j++) {
console.log("i = " + i + ", j = " + j);
}
}
Expected Output
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
For every outer loop iteration, the inner loop executes twice. In total, the inner body executes six times.
8. Using Break in a For Loop
The break statement immediately exits
the nearest enclosing loop.
Example
for (let i: number = 1; i <= 10; i++) {
if (i === 6) {
break;
}
console.log(i);
}
Expected Output
1
2
3
4
5
When i becomes 6, the break statement
terminates the loop. The value 6 is not printed.
9. Using Continue in a For Loop
The continue statement skips the
remaining statements in the current iteration
and proceeds to the next iteration.
Example
for (let i: number = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
Expected Output
1
2
4
5
The number 3 is skipped, but the loop continues and prints 4 and 5.
10. Loop Through a String
A for loop can access characters in a string by using the string's index.
Example
let language: string = "JAVA";
for (let i: number = 0; i < language.length; i++) {
console.log(language[i]);
}
Expected Output
J
A
V
A
The loop reads each character using its index. It stops when the index reaches the string length.
11. For Loop vs forEach()
TypeScript supports regular for loops and array
iteration methods such as forEach().
Both can process array elements.
Using a For Loop
let courses: string[] = ["Java", "Python", "Dot Net"];
for (let i: number = 0; i < courses.length; i++) {
console.log(courses[i]);
}
Using forEach()
let courses: string[] = ["Java", "Python", "Dot Net"];
courses.forEach(course => {
console.log(course);
});
Expected Output for Both
Java
Python
Dot Net
| Feature | For Loop | forEach() |
|---|---|---|
| Index control | Directly controlled by the loop. | Index can be provided to the callback. |
| Break support | Can use break. | Cannot directly stop iteration using break. |
| Common use | Custom loop control and counting. | Processing each array element. |
Practical Example: CIIT Student Marks
Let's calculate the total marks and average marks of a student using a for loop.
Example
let studentName: string = "Priya";
let marks: number[] = [80, 75, 90, 85, 70];
let totalMarks: number = 0;
for (let i: number = 0; i < marks.length; i++) {
totalMarks += marks[i];
}
let averageMarks = totalMarks / marks.length;
console.log("Student: " + studentName);
console.log("Total Marks: " + totalMarks);
console.log("Average Marks: " + averageMarks);
Expected Output
Student: Priya
Total Marks: 400
Average Marks: 80
The loop adds all five subject marks. The total is then divided by the number of subjects to calculate the average.
Common Mistakes
- Forgetting to update the loop counter.
- Using the wrong condition and repeating too many or too few times.
- Accessing an array index outside the valid range.
-
Confusing
i < array.lengthwithi <= array.length. - Accidentally creating an infinite loop.
- Confusing the behavior of break and continue.
Practice Task
Create a TypeScript program to perform the following tasks.
- Print numbers from 1 to 10.
- Calculate the sum of numbers from 1 to 10.
- Print the multiplication table of 7.
- Print all student names from an array.
Hint
let sum: number = 0;
for (let i: number = 1; i <= 10; i++) {
sum += i;
}
console.log("Sum: " + sum);
let number: number = 7;
for (let i: number = 1; i <= 10; i++) {
console.log(number + " x " + i + " = " + (number * i));
}
let students: string[] = ["Rahul", "Priya", "Amit"];
for (let i: number = 0; i < students.length; i++) {
console.log(students[i]);
}
Expected Output - Sum
Sum: 55
Expected Output - Student Names
Rahul
Priya
Amit
Summary
In this lesson, we learned how for loops work, how to use initialization, conditions, and updates, and how to process arrays, calculate totals, print multiplication tables, use nested loops, and control iterations with break and continue.
Key Point: A for loop is especially useful when repeating an operation a known number of times or iterating through an array using indexes.