Multiple ways to use for loops to iterate objects in typescript(all Examples)

Every programming language offers iteration features. The for loop is one such method for iteration.

TypeScript For Loop Tutorials

TypeScript also facilitates looping over specific iterations for executing code blocks. The for loop is used to iterate through elements from an array, map, set, and objects.

There are numerous methods for implementing for loops for iterating through elements.

TypeScript offers various variations and iterations.

Basic For Loop in TypeScript

This is a basic normal for loop in TypeScript.

for(initial Value; condition; counterValue){
// code block
}

It contains the for keyword followed by four statements enclosed in parentheses.

Three statements are enclosed in braces and separated by semicolons:

  • initial Value: is used to initialize the value.
  • Condition expression: It checks and returns the truth value. If it is true, code block statements are executed. If false, the for loop breaks the execution.
  • CounterValue: Used to increment/decrement the value of the variable.

Here is a for loop example:

In this loop, First, it is initialized with i=1, and the code block body executes as long as condition <= 5 is true, and the value (i) is increased by 1 using i++.

for (var i = 1; i <= 5; i++) {
  console.log("test");
}

This loop executes 5 times and outputs the string test five times.

Limitations:

  • The break and continue keywords do not function within this loop syntax.
  • Values are not returned inside the loop using the return keyword.

TypeScript For-in Loop Examples

It is another method for iterating arrays using indexes and is utilized to iterate enumerable objects. Any object that possesses enumerable properties, such as an array or JSON strings, can be iterated through using this loop.

Syntax:

for (var variable in collection) {
}

The variable is declared using the var or let keyword, and the type of variable can be string, number, or any other supported type.

Here is an example of a loop for the iteration of the array.

let arrayData = [8, 9, 13];
for (let element in arrayData) {
  console.log(typeof element); //string string string
  console.log(element); //0 1 2
  console.log(arrayData[element]); //8 9 13
}

For in-loop Limitations:

  • It iterates over the keys of objects, not the elements directly. In the case of arrays, it returns indexes, not actual elements.
  • The value is an index, which is of type string, not number. Therefore, when adding numbers with this value, concatenation occurs instead of addition, i.e., "1" + "2" = "12" instead of 3.

For-of Loop in TypeScript

ES6 introduced the for-of loop syntax, and TypeScript incorporated the same mechanism with the for...of loop. It is utilized for iterating over enumerable objects like arrays and strings.

Here, objects that are enumerable include strings and arrays.

syntax:

for (let/var variable of object) {}

for of loop Example:

let str = "This is a for...of loop example";
for (var character of str) {
  console.log(character); // This is a for...of loop example
}

It offers a simple and straightforward way of iteration with this syntax, addressing the limitations of both for and for...in loops.

For-of Loop Limitations:

  • The return, break, and continue keywords work as expected.
  • The for...of loop only operates on the iteration of strings and arrays. However, this limitation is anticipated to be removed in future TypeScript versions.

TypeScript For Loop Examples

Let’s explore some examples.

  • Iterate Object Keys and Values Using For Loop:

Objects contain keys and values; object keys can be iterated using a for...in loop.

// Looping through object keys
const Employee = {
  name: "Eric",
  id: 1,
  salary: 6000,
};

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

Another way to iterate an object’s values is using the Object.values method:

const Employee = {
  name: "Eric",
  id: 1,
  salary: 6000,
};
// Iterate object values
for (const value of Object.values(Employee)) {
  console.log(value);
}

A third approach, if you want to iterate keys and values in ES6, is to use Object.entries. Object.entries() loops through each item, returning an item. Then, using ES6 destructuring syntax, it converts them into keys and values.

const Employee = {
  name: "Eric",
  id: 1,
  salary: 6000,
};
// Iterate with key and value
for (const [key, value] of Object.entries(Employee)) {
  console.log(`${key}: ${value}`);
}
  • Iterate Values in a Set:

A Set is a data structure that does not allow duplicates and is not ordered.

const set = new Set([11, 21, 13, 14, 45]);

for (const value of set) {
  console.log(value);
}
  • Map Loop Example This example demonstrates how to iterate the keys and values of a Map object.
// Map iterate
const numbers = new Map([
  ["1", "one"],
  ["2", "two"],
  ["3", "three"],
]);

for (const [key, value] of numbers) {
  console.log(`${key} : ${value}`);
}

Difference between for…in and for…of Loops

  • Use for of loop for any iterable types

    Use the for...of loop for any iterable types. The for…in loop is used for iterating over enumerable keys of an object. It returns an index if the object is an array.

    let numbers = ["one", "two", "three"];
    for (let key in numbers) {
      console.log(key);
    }
    

    This prints 0, 1, 2.

    The for...of loop is used for iterating over enumerable values of an object, whether it’s a string, array, or object. If data is added to the array, it won’t be printed. This means that changes to the array prototype won’t affect the result.

    The for…in loop is not recommended for use with arrays.

    let numbers = ["one", "two", "three"];
    
    numbers.four = "four";
    
    // elKey represents the property keys
    for (let key in numbers) {
      console.log(key);
    }
    

    This prints one, two, three. If you modify an object, it will appear in the loop iteration. It is recommended for any enumerable properties.

  • Destructuring with for loop: The for...of loop works with destructuring an item, whereas the loop does not.

    // iterate using index and value
    for (const [index, values] of numbers.entries()) {
      console.log(index + ": " + values);
    }
    

Conclusion

You have learned about different variations of the for loop in TypeScript to iterate over enumerable objects such as arrays, strings, sets, and JSON objects, with examples including:

  • Normal for loop
  • For…in loop
  • For…of loop