How to use for...of loop in JavaScript with examples?
How to use for...of loop in JavaScript with examples?
354
01-Nov-2023
Updated on 02-Nov-2023
Aryan Kumar
02-Nov-2023Using 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:
Example 1: Iterating over an Array
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
Here, the for...of loop iterates through the characters of the string "Hello" and logs each character.
Example 3: Iterating over a Map
In this example, we iterate through the key-value pairs of a Map using the for...of loop.
Example 4: Custom Iterable Object
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.