For Loop in TypeScript
TypeScript's for loops are your trusty companions on the journey of repetitive tasks. They allow you to efficiently iterate through sequences of data, performing the same operation on each element.
Traditional for loop
The traditional for loop is similar to loops in other C-like languages. It has three parts: initialization, condition, and increment/decrement.
This example initializes a variable i to 0, iterates while i is less than 5, increments i in each iteration, and prints the value of i.
Looping through an array
This loop iterates through the fruits array. Instead of using an index, it uses the for-of syntax to directly access each element as fruit. This is a cleaner way to loop through collections.
Looping with object properties
This loop iterates through the object's properties. The for-in syntax provides the property names in each iteration. You can access the corresponding values using indexing with user[key].
Advanced loop control
This loop demonstrates advanced control mechanisms. First, it iterates from 10 to 0 (reverse order). Inside the loop, the continue statement skips even numbers by ignoring them and moving to the next iteration. This showcases selective execution within the loop.
Nested loops
This example uses nested loops. The outer loop iterates through the rows, and the inner loop iterates through the columns. This allows for multi-dimensional iteration patterns.
for...of loop
The for...of loop is used for iterating over iterable objects, such as arrays, strings, or other iterable collections.
In this example, the for...of loop iterates over each element in the colors array, assigning the current element to the variable color, and then prints each color.
for...in loop
The for...in loop is used for iterating over the properties of an object.
Here, the for...in loop iterates over the properties of the person object, and for each property, it prints both the key and the corresponding value.
These for loops provide flexibility in handling different types of iteration scenarios. The traditional for loop is versatile and can be used for various scenarios, while for...of is specifically designed for iterating over iterable values, and for...in is used for iterating over object properties.
Conclusion
The for loops provide versatile mechanisms for iteration. The traditional for loop is used for numeric iterations, for...of is designed for iterating over iterable objects like arrays, and for...in is used to loop through the properties of an object.