Basics
TS For...Of
Iterating with For...Of
TypeScript for...of iterates typed arrays ensuring type safety.
Introduction to For...Of Loop in TypeScript
The for...of loop in TypeScript is a powerful tool for iterating over iterable objects, such as arrays, strings, maps, and sets. Unlike traditional loops, for...of provides better readability and ensures type safety when working with typed arrays.
In this guide, we'll explore how to use for...of in TypeScript, with examples to illustrate its advantages and use cases.
Basic Syntax of For...Of
The syntax for the for...of loop is straightforward and easy to use. Here's the basic structure:
Here, element
represents each item in the iterable during each iteration.
Iterating Over Arrays
One of the most common use cases for for...of is iterating over arrays. TypeScript's type system ensures that the elements are of the correct type, reducing runtime errors.
In this example, the for...of loop iterates over the numbers
array, logging each number to the console.
Working with Strings
The for...of loop can also iterate over strings, treating each character as an element of the iterable.
This example demonstrates iterating over a string, where each character is accessed individually.
Iterating Over Maps and Sets
The for...of loop is not limited to arrays and strings; it can also iterate over Map
and Set
objects.
The above code snippets demonstrate how to iterate over a Map
to access key-value pairs and a Set
to access values.
Advantages of Using For...Of
The for...of loop offers several benefits:
- Readability: The syntax is clean and easy to understand.
- Type Safety: TypeScript ensures elements are of the expected type.
- Simplicity: There's no need to manage loop counters or indices.
These advantages make for...of a preferred choice when iterating over collections in TypeScript.
Conclusion
In this article, we've explored the for...of loop in TypeScript, covering its syntax, use cases, and advantages. By leveraging TypeScript's type system, for...of ensures type safety and simplifies array and collection iteration.
Continue to the next post in this series to learn about the for...in loop.