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

Every programming language provides iteration features. For loop is one of the ways to do iteration.

Typescript for loop tutorials

Typescript also provides a loop over specific times for executing code blocks. For Loop is used to iterate the elements from an array, map, set, and objects.

There are many ways we can do for loop for the iteration of elements.

Typescript provides different variations or 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 including parenthesis.

Three statements are enclosed in braces and separated by semicolons.

  • The 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, for loop breaks the execution
  • Counter value - 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:

  • break and continue keywords will not work in this loop syntax.
  • value is not returned inside the loop using the return keyword

Typescript For-in loop examples

It is another way to iterate arrays using indexes. It is used to iterate enumerable objects. Any object which has a property of enumerable elements like an array, or JSON strings enumerable objects are kind of object properties.

Syntax:

for (var variable in collection) {
}

the variable is declared using the var or let keyword and the type of variable is string or number or any supported type

Here is For in loop Example.

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:

  • Actually, It will not iterate over elements and iterates over the keys of the objects. In the case of arrays, you will get indexes, not actual elements
  • value is an index which is of type string, not number, so when you are adding numbers with this value gives append not adding numbers. ie "1"+"2"= 12 instead of 3 value

for of the loop in typescript

Es6 introduced the for of loop syntax. Typescript introduced the same for...of loop mechanism. It is used to do an iteration of enumerable objects like array and strings.

Here objects are enumerable that are strings, and arrays.

syntax:

for(let/var variable of object){}

for of loop Example:

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

It is a simple and easy way of doing iteration with this syntax. All the limitations for and for...in loops are solved with this.

for of loop Limitations:

  • The return, break, and continue keywords works as expected.
  • for…of loop only works on the iteration of strings and array. It is a limitation that is removed in future typescript versions.

Typescript for loop examples

Let’s see some examples

  • Iterate object keys and values using for loop:

Object contains keys and values, Object keys can be iterated using 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 using the object.values method

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

The third way is if you want to iterate keys and values in the ES6, Use object.entries object.entries() loop each item, return an item. And use ES6 destruction syntax, converted to 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:

Set is a data structure, that does not allow duplicate, not ordered.

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

for (const value of set) {
  console.log(value);
}
  • Map loop with example:

This example contains how to iterate the key 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 loop

  • Use for of loop for any iterable types for in loop used for iterating enumerable keys of an object. It returns an index if an object is an array.
let numbers = ["one", "two", "three"];
for (let key in numbers) {
  console.log(key);
}

It prints 0,1,2.

for of loop is used for iterating enumerable values of an object. an object is a string, array, or object. If you add data to the array, It does not print. It means, that if there is a change to the array prototype, It does not appear in the result.

for in loop not recommended to use for arrays,

let numbers = ["one", "two", "three"];

numbers.four = "four";

// elKey are the property keys
for (let key in numbers) {
  console.log(key);
}

It prints one, two, three. If you modify an object, It appears in loop iteration.

It is recommended for any enumerable properties.

  • Destructing with for loop

for of loop works with destructing an item. for in loop does not work.

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

Conclusion

You learned different variations of for loop in typescript to iterate enumerable objects like an array, strings, set, and json objects with examples.

  • normal for loop
  • for-in loop
  • for of loop