Languages
[Edit]
EN

TypeScript - how to use foreach?

0 points
Created by:
evangeline
420

In this article, we're going to have a look at how to use for-each loop in TypeScript.

Quick solution:

There are 3 ways how we can do it:

  • for-of loop to work with arrays,
  • for-in loop to work with arrays and objects,
  • forEach method to work with arrays.

See below examples to see practical examples.

1. for-each with arrays examples

Edit

This section shows how to use shortened loop construction iterating over arrays.

1.1. for-of loop example

Edit

This section shows how to use for-of loop construction to iterate over array.

Output:

Note: for-of loop was introduced in ES6 (ECMAScript 2015).

1.2. for-in loop example

Edit

This section shows how to use for-in loop construction to iterate over the array.

Output:

Note: using for-in loop with array is risky because of possible additional array properties - array.hasOwnProperty(key) method solves the problem.

1.3. forEach method example

Edit

This section shows how to use forEach method to iterate over an array.

Output:

Note: Array.prototype.forEach method was introduced in ES5 (ECMAScript 2009).

2.  for-in with objects examples

Edit

This section shows how to use for-in loop construction to iterate over object properties. It is very important to use hasOwnProperty method to check if each property is part of the iterated object.

Output:

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join