Just so you know, TypeScript does indeed support loops. You could rewrite the previous example with classic loops. Although, we do not recommend it, since forEach and lambdas, in general, are very expressive, concise, and readable (after a bit of getting used to).
In TypeScript, objects are considered to be iterable if they have an implementation for the Symbol.iterator property. This probably isn't very clear, but the following built-in types do have that implementation: Array, Map, Set, String, Int32Array, and UInt32Array. The Symbol.iterator function is called by loops to get the list of values to iterate on.
TypeScript supports two interesting for loop forms:
- for..of: Loops over the values of an iterable object, invoking the Symbol.iterator property on it to get those values
- for..in: Loops over a list of keys on the object
An important distinction between for..of and for..in is also that for..in works with any object while for..of only works with iterables.
Here's an example:
const todoList: string[] = ["A", "B", "C"]; for (let item in todoList) { console.log(item); // 0, 1, 2 // keys } for (let item of todoList) { console.log(item); // "A", "B", "C" // values }
In addition, TypeScript also supports classic for loops:
const numbers = [1, 2, 3]; for (let val = 0; val < numbers.length; val++) { const number = numbers[val]; console.log(number); // 1 2 3 }
This last form is what the TypeScript compiler transforms for..of loops into when it targets ES5 and ES3. This is explained here in detail: https://www.typescriptlang.org/docs/handbook/iterators-and-generators.html.
Based on this information, you should be able to easily rewrite the updateTodoList function to use a for..of loop.
Finally, note that TypeScript also supports the while and do..while loops, even if they are seldom used:
let count = 5; while (count > 0) { console.log("Counting downwards: ", count); count--; } do { console.log("Counting upwards: ", count); count++; } while (count <= 5);