JavaScript Iterables

By | August 26, 2022

Iterables are iterable objects (like Arrays).

Iterables can be accessed with simple and efficient code.

Iterables can be iterated over with for..of loops

The For Of Loop

The JavaScript for..of statement loops through the elements of an iterable object.

Syntax

for (variable of iterable) {
  // code block to be executed
}

Iterating

Iterating is easy to understand.

It simply means looping over a sequence of elements.

Here are some easy examples:

  • Iterating over a String
  • Iterating over an Array

Iterating Over a String

You can use a for..of loop to iterate over the elements of a string:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Iterables</h2>
<p>Iterate over a String:</p>
<p id="demo"></p>
<script>
// Create a String
const name = "W3Schools";
// List all Elements
let text = ""
for (const x of name) {
  text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result:

JavaScript Iterables

Iterate over a String:

W
3
S
c
h
o
o
l
s

Iterating Over an Array

You can use a for..of loop to iterate over the elements of an Array:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Iterables</h2>
<p>Iterate over an Array:</p>
<p id="demo"></p>
<script>
// Create aa Array
const letters = ["a","b","c"];
// List all Elements
let text = "";
for (const x of letters) {
  text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result:

JavaScript Iterables

Iterate over an Array:

a
b

Iterating Over a Set

You can use a for..of loop to iterate over the elements of a Set:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Iterables</h2>
<p>Iterate over a Set:</p>
<p id="demo"></p>
<script>
// Create a Set
const letters = new Set(["a","b","c"]);
// List all Elements
let text = "";
for (const x of letters) {
  text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result:

JavaScript Iterables

Iterate over a Set:

a
b
c

Sets and Maps are covered in the next chapters.

Iterating Over a Map

You can use a for..of loop to iterate over the elements of a Map:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Iterables</h2>
<p>Iterate over a Map:</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
  ["apples", 500],
  ["bananas", 300],
  ["oranges", 200]
]);
// List all entries
let text = "";
for (const x of fruits) {
  text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result:

JavaScript Iterables

Iterate over a Map:

apples,500
bananas,300
oranges,200

Leave a Reply

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