Mastering Loops in TypeScript: A Complete Guide
Introduction
Loops are an essential part of any programming language, and TypeScript is no different. They are powerful tools that allow developers to execute a block of code multiple times without having to write repetitive statements. Instead of manually repeating code, loops let you automate the process through a structure that comprises three fundamental parts:
- Initialization – Setting a starting point.
- Condition – Checking if the loop should continue.
- Increment/Decrement – Updating the loop variable to move towards termination.
In this tutorial, we will dive deep into the various looping structures available in TypeScript: while
, do...while
, for
, for...in
, and for...of
. We’ll explore their syntax, use-cases, and the key differences between them, especially when dealing with arrays and objects.
1. While Loop
The while
loop evaluates a condition before executing the block of code. If the condition is true, the code inside the loop runs.
Syntax:
while (condition) {
// code block
}
Example:
let i: number = 0; // Initialization
while (i <= 10) { // Condition
console.log(i);
i++; // Increment
}
Output:
0 1 2 3 4 5 6 7 8 9 10
Use Case:
Useful when the number of iterations isn’t known in advance and depends on dynamic conditions.
2. Do…While Loop
This loop is similar to the while
loop, but it checks the condition after executing the block once. So, it runs at least one time.
Syntax:
do {
// code block
} while (condition);
Example:
let i = 0;
do {
console.log(i);
i++;
} while (i <= 10);
Output:
0 1 2 3 4 5 6 7 8 9 10
Use Case:
When the block should be executed at least once before the condition is tested.
3. For Loop
The most commonly used loop that includes initialization, condition, and increment/decrement in a single line.
Syntax:
for (initialization; condition; increment/decrement) {
// code block
}
Example:
for (let i: number = 1; i <= 10; i++) {
console.log(i);
}
Output:
1 2 3 4 5 6 7 8 9 10
Use Case:
Best when the number of iterations is known ahead of time.
4. For…in Loop
The for...in
loop is used to iterate over the keys or indices of an object or array.
Syntax:
for (const key in object) {
// code block
}
Example with Array:
const fruits = ["apple", "banana", "cherry"];
for (const index in fruits) {
console.log(index); // Outputs index: 0, 1, 2
}
Example with Object:
const person = { name: "John", age: 30, city: "New York" };
for (const key in person) {
console.log(key + ": " + person[key]);
}
Output:
name: John
age: 30
city: New York
Use Case:
Used for objects or arrays when you need to access keys or property names.
5. For…of Loop
The for...of
loop is used to iterate over values in iterable objects such as arrays, strings, maps, etc.
Syntax:
for (const value of iterable) {
// code block
}
Example:
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color); // Outputs: red, green, blue
}
Use Case:
Perfect for retrieving values from arrays, strings, or collections.
6. Difference Between for...in
and for...of
Feature | for…in | for…of |
---|---|---|
Iterates Over | Keys (indexes or property names) | Values (of iterable objects) |
Suitable For | Objects and Arrays | Arrays, Strings, Sets, Maps |
Output | Index or key | Value at index or in set |
Use Case | Enumerating object properties | Looping through array values |
Example Comparison:
const pets = ["dog", "cat", "rabbit"];
for (const i in pets) {
console.log(i); // Outputs: 0, 1, 2
}
for (const pet of pets) {
console.log(pet); // Outputs: dog, cat, rabbit
}
Summary
In TypeScript, loops are powerful tools that help you execute repetitive tasks efficiently. Whether you need a simple numeric iteration with a for
loop, or you need to go through keys in an object using for...in
, or loop over array values using for...of
, TypeScript provides the flexibility to handle all scenarios.
Key Takeaways:
while and
do…while are great when the number of iterations is not fixed.
for loops are ideal for known, fixed repetitions.
for…in is best for accessing object properties or array indices.
for…of is best for accessing array values or iterables.
Understanding and mastering loops will significantly enhance your ability to write concise, clean, and effective TypeScript code. Keep practicing with different data structures and you’ll become a loop pro in no time!
🔁 10 TypeScript Programming Assignments on Loops
🔄 Assignment 1: Print 1 to 10 (For Loop)
Write a program using a for
loop that prints numbers from 1 to 10.
✅ Bonus: Print in reverse using the same logic.
🔄 Assignment 2: Sum of First N Numbers
Take a number n
and use a for
loop to find the sum of numbers from 1 to n
.
✅ Example: For n = 5
, output should be 15
.
🔄 Assignment 3: Even and Odd Checker
Use a for
loop to print whether each number between 1 and 20 is even or odd.
✅ Use the modulus operator %
.
🔄 Assignment 4: Multiplication Table Generator
Ask the user for a number and print its multiplication table up to 10 using a for
loop.
✅ Example: 5 × 1 = 5 … up to 5 × 10 = 50.
🔄 Assignment 5: Factorial Calculator (While Loop)
Use a while
loop to calculate the factorial of a number.
✅ Example: 5! = 120
🔄 Assignment 6: Reverse a Number
Use a while
loop to reverse the digits of a number.
✅ Example: Input 1234
, Output 4321
.
🔄 Assignment 7: Password Attempts (Do-While Loop)
Ask the user to enter a password. If it’s incorrect, allow retrying up to 3 times using a do-while
loop.
✅ End with success or failure message.
🔄 Assignment 8: Print Elements of an Array
Create an array of fruits and print each item using a for...of
loop.
✅ Try with for...in
and observe the difference.
🔄 Assignment 9: Find Largest in Array
Use a loop to find the largest number in an array.
✅ Example: [3, 8, 1, 9, 2]
→ Output: 9
🔄 Assignment 10: Nested Loops – Pattern Printer
Write a program using nested for
loops to print the following pattern:
*
* *
* * *
* * * *
✅ Try increasing or reversing the pattern.