Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk3 min

How to Use for…of Loops in TypeScript

Use TypeScript’s for...of loop to process iterable values, from array elements to map entries. Learn how it differs from for...in and what to check when compiler targets cause errors.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use for...of when you want to process each value in an array or another iterable, one at a time:

const values = [1, 2, 3];
for (const value of values) {
  console.log(value);
}

The loop gets values from the iterable’s Symbol.iterator implementation. That means arrays work, as do built-in iterables such as maps, sets, strings and typed arrays. Ordinary objects are not automatically iterable.

As an Amazon Associate I earn from qualifying purchases.

How do I use a for...of loop in TypeScript?

Place the iterable after of and declare a variable that receives each value in turn. TypeScript infers the variable’s type from the iterable:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const names = ["Ada", "Grace"];
for (const name of names) {
  console.log(name);
}

Here, name is inferred as a string. Use const when you do not reassign the loop variable; use let if you need to reassign that binding inside the loop body.

What can for...of iterate?

for...of works with iterables: objects that provide a Symbol.iterator implementation. The TypeScript handbook lists arrays, maps, sets, strings and typed arrays among built-in iterables. A plain object with properties is not iterable just because it has keys.

For a function that should accept different iterable collections, type its input as Iterable<X>, where X is the element type:

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
function toArray<X>(xs: Iterable<X>): X[] {
  return [...xs];
}

This accepts arrays and other values that implement the iterable protocol. See the TypeScript handbook’s iterator and generator documentation for the protocol and additional examples.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What is the difference between for...of and for...in?

Use for...of for values and for...in for property names. With an array, for...in produces index-like strings, while for...of produces the array elements:

const list = [4, 5, 6];

for (const index in list) {
  console.log(index); // "0", "1", "2"
}

for (const value of list) {
  console.log(value); // 4, 5, 6
}

for...in also applies to objects generally. for...of requires an iterable, so it is the right choice when the code needs each collection value rather than its property name.

Can I use for...of with a Map or Set?

Yes. Maps and sets are built-in iterables, so they can be used directly after of. A map loop yields entries; a set loop yields its values:

const scores = new Map([["Ada", 10], ["Grace", 12]]);
for (const [name, score] of scores) {
  console.log(name, score);
}

const tags = new Set(["typescript", "javascript"]);
for (const tag of tags) {
  console.log(tag);
}

Why does for...of give an error with my TypeScript target?

The TypeScript target affects the JavaScript that the compiler emits and which iteration behavior it can support. The handbook documents that ES5-targeted output permits iterator use only on values of Array type, even if a non-array object implements Symbol.iterator. For an ES2015-compliant target, TypeScript emits for...of to use the runtime’s built-in iterator implementation. Check both the project’s compiler configuration and the JavaScript runtime where the output will run; compiler output cannot make a runtime support features it lacks. The official handbook describes these target-dependent behaviors.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What does downlevelIteration do?

The downlevelIteration compiler option was designed to make iteration features more closely emulate ES6 behavior in ES5 environments. When Symbol.iterator exists, its helper can use that implementation; without it, the helper falls back to other behavior. The option does not install Symbol.iterator or add a runtime polyfill. See the official option reference.

Version matters when following older advice: the TypeScript 6.0 release notes deprecate both target: es5 and downlevelIteration. They recommend using an external compiler or post-processing if ES5 output remains necessary. Check the TypeScript 6.0 release notes alongside the compiler version used by your project.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.