The use of for looping in JavaScript is pretty easy and straight forward but in TypeScript there is some nuances that you need to know. I got stuck find a way to better understand and type in loops in TypeScript. Hope it helps you as well. Let’s check it out.

How to write a for loop in TypeScript

# Simple for loop

To use for you need an object that have correct implemented or built-in [Symbol.iterator](https://www.typescriptlang.org/docs/handbook/symbols.html#symboliterator) for like ArrayMapSetStringInt32ArrayUint32Array to iterate over.

const fruitsArray = ["apple", "orange", "grape"]

for (let fruit of fruitsArray) {
    console.log(fruit); // "apple", "orange", "grape"
}

# for..of vs. for..in statements

Both for..of and for..in statements iterate over objects with Symbol.iterator implemented. The values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.

Example with a list:

for (let fruit of fruitsArray) {
    console.log(fruit); // "apple", "orange", "grape"
}

for (let fruit in fruitsArray) {
    console.log(fruit); // "0", "1", "2"

#looping #type #javascript #typescript

Typescript Iterators - “for” Loop Statement
1.05 GEEK