TypeScript - how to use foreach?
In this article, we're going to have a look at how to use for-each loop in TypeScript.
Quick solution:
const array: string[] = ['item 1', 'item 2', 'item 3'];
array.forEach((item: string, index: number): void => {
console.log('index ' + index + ': ' + item);
});
// or
for (const item of array) {
console.log(item);
}
There are 3 ways how we can do it:
for-ofloop to work with arrays,for-inloop to work with arrays and objects,forEachmethod to work with arrays.
See below examples to see practical examples.
1. for-each with arrays examples
This section shows how to use shortened loop construction iterating over arrays.
1.1. for-of loop example
This section shows how to use for-of loop construction to iterate over array.
const array: string[] = ['item 1', 'item 2', 'item 3'];
for (const item of array) {
console.log(item);
}
Output:
item 1
item 2
item 3
Note:
for-ofloop was introduced in ES6 (ECMAScript 2015).
1.2. for-in loop example
This section shows how to use for-in loop construction to iterate over the array.
const array: string[] = ['item 1', 'item 2', 'item 3'];
for (const key in array) {
if (array.hasOwnProperty(key)) {
console.log(array[key]);
}
}
Output:
item 1
item 2
item 3
Note: using
for-inloop with array is risky because of possible additional array properties -array.hasOwnProperty(key)method solves the problem.
1.3. forEach method example
This section shows how to use forEach method to iterate over an array.
const array: string[] = ['item 1', 'item 2', 'item 3'];
array.forEach((item: string, index: number): void => {
console.log('index ' + index + ': ' + item);
});
Output:
index 0: item 1
index 1: item 2
index 2: item 3
Note:
Array.prototype.forEachmethod was introduced in ES5 (ECMAScript 2009).
2. for-in with objects examples
This section shows how to use for-in loop construction to iterate over object properties. It is very important to use hasOwnProperty method to check if each property is part of the iterated object.
interface MyObject {
key1: string;
key2: string;
key3: string;
}
const object: MyObject = {
key1: 'value 1',
key2: 'value 2',
key3: 'value 3',
};
for (const key in object) {
if (object.hasOwnProperty(key)) {
const value: string = object[key];
console.log(key + ': ' + value);
}
}
Output:
key1: value 1
key2: value 2
key3: value 3