JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript for…of Loop

8 April 2025 | Category:

The for...of loop is used to iterate over iterable objects like arrays, strings, maps, sets, and more.
It gives you the values directly, not the indexes or keys.


✅ Syntax

for (let item of iterable) {
  // Code to run
}
  • iterable can be an array, string, set, etc.
  • item is the current value in the loop.

🔢 Example: Loop Through an Array

let fruits = ["apple", "banana", "cherry"];

for (let fruit of fruits) {
  console.log(fruit);
}

Output:

apple
banana
cherry

🔤 Looping Through a String

let word = "Hello";

for (let letter of word) {
  console.log(letter);
}

Output:

H
e
l
l
o

✅ Better Than for...in for Arrays

Unlike for...in, which gives you indexes, for...of gives you values — cleaner and more readable.

for...in vs for...of on arrays:

let colors = ["red", "green", "blue"];

for (let i in colors) {
  console.log(i); // Outputs: 0, 1, 2
}

for (let color of colors) {
  console.log(color); // Outputs: red, green, blue
}

🧠 Can You Use it on Objects?

No, you can’t use for...of directly on plain objects.

let obj = {name: "John", age: 30};

// ❌ This will cause an error:
// for (let x of obj) {
//   console.log(x);
// }

✅ Instead, convert the object to an array using Object.keys(), Object.values(), or Object.entries():

let person = {name: "Alice", age: 22};

for (let value of Object.values(person)) {
  console.log(value);
}

🧾 Summary

Featurefor...of Loop
Used forArrays, strings, sets, maps
OutputValues
Use on object?Not directly
Clean for loop✅ Best for arrays/strings