Typescript for loop
Created By: chatGPT
TypeScript is a superset of JavaScript, and using a
for
loop in TypeScript is quite similar to JavaScript. Here's how you can use a for
loop to iterate over an array: for loops are commonly used for executing a block of code a specific number of times. You can also track the index of each iteration.const numbers: number[] = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(`Number is: ${numbers[i]}`);
}
In this example, we declare an array of numbers. The loop initializes a variable
i
to 0
. As long as i
is less than the length of the array, the loop will continue. Inside the loop, we use console.log
to print each number to the console.// Output:
// Number is: 1
// Number is: 2
// Number is: 3
// Number is: 4
// Number is: 5
TypeScript also supports other types of loops, like
for...of
and for...in
, which are helpful for specific use cases. The for...of
loop is particularly useful for iterating over the values in an iterable. Here’s an example:const fruits: string[] = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(`Fruit: ${fruit}`);
}
In this case,
for...of
directly gives us each fruit in the array, allowing for cleaner and more readable code.// Output:
// Fruit: apple
// Fruit: banana
// Fruit: cherry
If you need to iterate over the properties of an object, you can use the
for...in
loop. Here is how to use it in TypeScript:const person = {
name: 'John',
age: 30,
city: 'New York'
};
for (const key in person) {
console.log(`Key: ${key}, Value: ${person[key]}`);
}
This loop iterates over each key in the
person
object and logs both the key and its corresponding value to the console.// Output:
// Key: name, Value: John
// Key: age, Value: 30
// Key: city, Value: New York