JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - for-of loop

The for-of loop provides a modern way to iterate over iterable objects in JavaScript, such as Arrays, Maps, Sets, and even Strings. This loop simplifies the process of traversing collections by directly providing access to the values rather than the indexes or keys. It's particularly useful for cases where you need to work with the elements of a collection directly and do not require access to the index or key.

Syntax

The syntax of the for-of loop is straightforward and intuitive:

Javascript
Javascript
. . . .

Parameters

  • value: On each iteration, this variable holds the value of the current element in the iterable.
  • iterable: The collection being iterated over, which can be any iterable object (e.g., Array, Map, Set, String).

Example 1: Iterating Over an Array

Iterate over an array of numbers and print each number.

Javascript
Javascript

. . . .

This example demonstrates the for-of loop's straightforward approach to array iteration, directly accessing and printing each number without needing to use an index.

Example 2: Iterating Over a String

Iterate over each character in a string and print it.

Javascript
Javascript

. . . .

Here, the for-of loop simplifies string iteration, treating the string as a collection of characters and printing each one individually.

The for-of loop is a powerful addition to JavaScript, offering a simple and effective way to iterate over iterable objects. Its direct access to the elements of a collection makes it particularly useful for operations that require value manipulation, without the overhead of accessing values through keys or indexes. Understanding how to use the for-of loop will enhance your ability to work with various data structures in JavaScript efficiently.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next