How to Use for…in Loops in TypeScript?

In this tutorial, I will explain how to effectively use the for...in loop in TypeScript. This loop is particularly useful for iterating over the properties of an object. I will show you for…in loop syntax and also a few examples related to this.

What is a for…in Loop in TypeScript?

The for...in loop in TypeScript is a control flow statement that iterates over the enumerable properties of an object. This loop is ideal for scenarios where you need to access each property name (key) of an object.

Syntax of for…in Loop

The basic syntax of the for...in loop in TypeScript is as follows:

for (let key in object) {
    // code block to be executed
}

Here, key is a variable that will be assigned the value of each property name in the object, one at a time. The object is the object whose properties you want to iterate over.

Read For Loop in TypeScript

TypeScript for…in Loop Examples

Now, let me show you some examples of TypeScript for…in loop.

1. Iterate Over an Object

Let’s consider an example where we have an object representing a person from New York:

const person: { [key: string]: any } = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    city: "New York"
};

for (let key in person) {
    console.log(`${key}: ${person[key]}`);
}

In this example, the for...in loop iterates over the person object, logging each key-value pair to the console:

firstName: John
lastName: Doe
age: 30
city: New York

Here is the exact output in the screenshot below:

for…in Loops in TypeScript

You can also write the code like below:

const person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    city: "New York"
};

for (let key in person) {
    console.log(`${key}: ${person[key as keyof typeof person]}`);
}

Read How to Use for…of Loops in TypeScript?

2. Nested Objects

For more complex scenarios, consider an object with nested properties. For example, a company based in San Francisco:

const company: { [key: string]: any } = {
    name: "Tech Innovators",
    location: {
        city: "San Francisco",
        state: "California"
    },
    employees: 150
};

for (let key in company) {
    if (typeof company[key] === 'object') {
        for (let nestedKey in company[key]) {
            console.log(`${nestedKey}: ${company[key][nestedKey]}`);
        }
    } else {
        console.log(`${key}: ${company[key]}`);
    }
}

This example demonstrates how to handle nested objects within a for...in loop, ensuring all properties are accessed and logged.

Here is the exact output in the screenshot below:

TypeScript for…in Loop Examples

Best Practices

  1. Check for Inherited Properties: Use hasOwnProperty to ensure you are iterating over the object’s own properties, not inherited ones. for (let key in person) { if (person.hasOwnProperty(key)) { console.log(`${key}: ${person[key]}`); } }
  2. Avoid Using for…in with Arrays: The for...in loop is not suitable for arrays as it iterates over the array indices as strings, which may not be the intended behavior. Use for...of or traditional for loops for arrays.
  3. Performance Considerations: Be mindful of performance, especially with large objects or nested structures. Ensure your loops are optimized and avoid unnecessary operations within the loop body.

Conclusion

The for...in loop in TypeScript is a powerful tool for iterating over object properties. By understanding its syntax and best practices, you can write efficient and readable code. Whether you’re working with simple objects or complex nested structures, the for...in loop provides a straightforward way to access and manipulate object properties.

You may also like: