---
title: "How to use for...of loop in JavaScript with examples?"  
description: "How to use for...of loop in JavaScript with examples?"  
author: "Revati S Misra"  
published: 2023-11-01  
updated: 2023-11-02  
canonical: https://www.mindstick.com/forum/160376/how-to-use-for-of-loop-in-javascript-with-examples  
category: "javascript"  
tags: ["javascript", "iterable"]  
reading_time: 2 minutes  

---

# How to use for...of loop in JavaScript with examples?

How to use [for...of loop](https://www.mindstick.com/forum/160375/what-is-the-purpose-of-using-the-for-of-loop-and-how-does-it-relate-to-iterables) in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript) with examples?

## Replies

### Reply by Aryan Kumar

Using a **for...of** loop in JavaScript is a convenient way to iterate over the elements of an iterable object, such as arrays, strings, and more. Here's an explanation with examples:

## Syntax:

```plaintext
for (variable of iterable) {
  // Code to be executed for each element in the iterable
}
```

## Example 1: Iterating over an Array

```plaintext
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
  console.log(fruit);
}
```

In this example, the **for...of** loop iterates through the **fruits** array and prints each element to the console.

## Example 2: Iterating over a String

```plaintext
const text = "Hello";
for (const char of text) {
  console.log(char);
}
```

Here, the **for...of** loop iterates through the characters of the string "Hello" and logs each character.

## Example 3: Iterating over a Map

```plaintext
const person = new Map();
person.set("name", "Alice");
person.set("age", 30);

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

In this example, we iterate through the key-value pairs of a Map using the **for...of** loop.

## Example 4: Custom Iterable Object

```plaintext
const iterableObject = {
  [Symbol.iterator]:
```

Here, we define a custom iterable object that yields values when iterated with a **for...of** loop.

The **for...of** loop is a versatile way to iterate through various data structures in JavaScript, making your code more concise and readable.


---

Original Source: https://www.mindstick.com/forum/160376/how-to-use-for-of-loop-in-javascript-with-examples

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
