Hello Friends 👋,
Welcome to Infinitbility.
Today, we will learn how many ways have to write for loops in typescript.
In this tutorial, we will see examples of simple for
, for.. of
, and for.. in
loop.
Let’s create a sample array of objects which we will use all for loops example.
interface User {
id: number;
name: string;
}
let users: Array<User> = [
{ id: 1, name: 'infinitbility' },
{ id: 2, name: 'notebility' },
{ id: 3, name: 'repairbility' },
];
TypeScript for loop
Let’s write our most used syntax, Yes for with their three statment.
interface User {
id: number;
name: string;
}
let users: Array<User> = [
{ id: 1, name: 'infinitbility' },
{ id: 2, name: 'notebility' },
{ id: 3, name: 'repairbility' },
];
for (let i = 0;i < users.length;i++) {
console.log("users", users[i])
}
TypeScript for of loop
The for.. of
loop same as for-each loop let’s see how we will use it in typescript.
interface User {
id: number;
name: string;
}
let users: Array<User> = [
{ id: 1, name: 'infinitbility' },
{ id: 2, name: 'notebility' },
{ id: 3, name: 'repairbility' },
];
for (let user of users) {
console.log("user", user)
}
The for..in
loop which returns the key of the array and of object let see, how we can use for..in
loop in typescript.
interface User {
id: number;
name: string;
}
let users: Array<User> = [
{ id: 1, name: 'infinitbility' },
{ id: 2, name: 'notebility' },
{ id: 3, name: 'repairbility' },
];
for (let user in users) {
console.log("users", users[user])
}
Thanks for reading…