Skip to content

JavaScript iterable | Data

  • by

JavaScript iterable is data structures that have the Symbol.iterator() method. For example, Arrays, Strings, Sets, etc. JavaScript iterable protocol mentions that an iterable should have the Symbol.iterator key.

The iterator protocol provides the next() method to access each element of the iterable (data structure) one at a time.

JavaScript iterable

Simple example code Iterating Over a String and Array. You can use the for...of loop to iterate through these.

<!DOCTYPE html>
<html>
<body>
  <script>
    // string
    for (const x of "Hello") {
      console.log(x)
    }

  // Array
  for (const x of [1,2,3]) {
    console.log(x)
  }
</script>
</body>
</html>

Output:

JavaScript iterable object

JavaScript next() Method

const arr = ['h', 'e', 'l', 'l', 'o'];

let arrIterator = arr[Symbol.iterator]();

console.log(arrIterator.next()); // {value: "h", done: false}
console.log(arrIterator.next()); // {value: "e", done: false}
console.log(arrIterator.next()); // {value: "l", done: false}
console.log(arrIterator.next()); // {value: "l", done: false}
console.log(arrIterator.next()); // {value: "o", done: false}
console.log(arrIterator.next()); // {value: undefined, done: true}

Do comment if you have any doubts or suggestions on this

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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