Typescript for...of loop
Created By: chatGPT
The
for...of
loop in TypeScript allows you to iterate over iterable objects, such as arrays, strings, maps, and sets. It's a more concise and readable alternative to the traditional for
loop. You can use it to access each element in a collection directly without the need for an index variable.const numbers = [10, 20, 30, 40];
for (const number of numbers) {
console.log(number);
}
for...of
can also be used with strings, allowing you to iterate over each character in the string. This makes it easier to handle string manipulation without using index-based access.const greeting = "Hello";
for (const char of greeting) {
console.log(char);
}
In addition to arrays and strings,
for...of
works with other iterable data structures like maps. When iterating over maps, it returns the values directly, but you can also iterate over entries or keys if needed.const map = new Map();
map.set('a', 1);
map.set('b', 2);
for (const value of map.values()) {
console.log(value);
}
for (const [key, value] of map.entries()) {
console.log(`${key}: ${value}`);
}
If you want to work with sets, the
for...of
loop can easily iterate through the unique values stored in a set. This is particularly useful for scenarios where duplicates are not allowed.const uniqueNumbers = new Set([1, 2, 3, 4, 4, 5]);
for (const num of uniqueNumbers) {
console.log(num);
}
Remember that the
for...of
loop only iterates over the values of the iterable object. If you need both the index and the value, consider using the forEach
method or a traditional for
loop instead.const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});