In TypeScript, you can implement for loops in multiple ways, and these approaches are also applicable to JavaScript, as TypeScript is a superset of JavaScript. Here are some common ways to use for loops; for each approach, I'll provide a simple example to illustrate its usage:
1. Basic for Loop
This is the most fundamental loop structure, commonly used when you need to execute operations sequentially or access arrays, lists, and similar structures.
typescriptfor (let i = 0; i < 5; i++) { console.log(i); }
2. for...of Loop
This approach is suitable for iterating over array elements or other iterable objects. It directly accesses the element values rather than the indices.
typescriptlet array = [10, 20, 30, 40, 50]; for (let value of array) { console.log(value); }
3. for...in Loop
The for...in loop is primarily used for iterating over object properties. This approach iterates over all enumerable properties of the object itself.
typescriptlet obj = {a: 1, b: 2, c: 3}; for (let key in obj) { console.log(key, obj[key]); }
4. Array.prototype.forEach()
Although forEach() is not a traditional for loop, it is commonly used for array iteration. It executes the provided function once for each element in the array.
typescriptlet numbers = [1, 2, 3, 4, 5]; numbers.forEach((number, index) => { console.log(number, index); });
Example Use Case
Suppose we need to calculate the length of each string in an array and store it in a new array. For this scenario, we can use the for...of loop, as it directly accesses each string in the array:
typescriptlet strings = ["hello", "world", "typescript"]; let lengths = []; for (let str of strings) { lengths.push(str.length); } console.log(lengths); // Output: [5, 5, 9]
These are the common ways to use for loops in TypeScript, each with its specific use cases and advantages. In actual development, we can choose the most appropriate loop structure based on specific requirements.